首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PowerMock忽略我从方法返回的内容

PowerMock忽略我从方法返回的内容
EN

Stack Overflow用户
提问于 2018-05-04 16:47:22
回答 1查看 138关注 0票数 0

我正在调用此方法,该方法返回一个空列表。

代码语言:javascript
复制
  public static List<String> getAttribute(@Nullable Subject subject, String key) {

      return Collections.emptyList();
    }

忽略此方法的简单性。

我有一个测试方法:

代码语言:javascript
复制
  @Test
  public void testGetRequesterGroupsOnSubject() {
      List<String> testData = new ArrayList<>();
      testData.add("admin");
    mockStatic(SecurityUtils.class);
    mock(SubjectUtils.class);
    doReturn(principalCollection).when(currentSubject).getPrincipals();
    doReturn(testData).when(SubjectUtils.getAttribute(currentSubject, SubjectUtils.ROLE_CLAIM_URI));
    assertEquals(sfa.getRequesterGroups(), new ArrayList<>());
  }

SubjectUtils是使用上述方法的类。然而,即使getAttribute返回一个空列表,我不应该期望它返回我的字符串列表吗?(testData)

当前错误:

代码语言:javascript
复制
org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at 

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
EN

回答 1

Stack Overflow用户

发布于 2018-05-10 14:10:00

我能够重现您的问题,并且当我使用when().thenReturn()而不是DoReturn().When()时,测试运行成功。

代码语言:javascript
复制
@RunWith(PowerMockRunner.class)
@PrepareForTest( SubjectUtils.class )
public class SubjectTest
{
  @Test
  public void testGetRequesterGroupsOnSubject() {
      List<String> testData = new ArrayList<>();
      testData.add("admin");  
      Subject subject = new Subject();      
      PowerMockito.mockStatic(SubjectUtils.class);
      PowerMockito.when(SubjectUtils.getAttribute(subject, "")).thenReturn(testData);
      //PowerMockito.doReturn(testData).when(SubjectUtils.getAttribute(subject, ""));
      assertEquals(SubjectUtils.getAttribute(subject, ""), testData);
  }
}

我想不出这种行为的原因。当我搜索时,这两种方法对于模拟对象似乎没有区别。

Unfinished Stubbing Detected in Mockito中有关于这个问题的详细描述,但我无法将其映射到这个案例中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50170830

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档