java - PowerMock 忽略我从方法返回
问题描述
我正在调用这个返回空列表的方法..
public static List<String> getAttribute(@Nullable Subject subject, String key) {
return Collections.emptyList();
}
忽略此方法的简单性。
我有一个测试方法:
@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 返回一个空列表,我不应该期望这会返回我的字符串列表吗?(测试数据)
当前错误:
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
解决方案
我能够重现您的问题,并且当我使用 when().thenReturn() 而不是 DoReturn().When() 时,测试成功运行。
@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);
}
}
我无法弄清楚这种行为的原因。当我搜索时,模拟对象的两种方法似乎没有区别。
在 Mockito 中检测到的未完成的存根中有此问题的详细描述, 但我无法将其映射到这种情况。
推荐阅读
- azure-active-directory - 返回“https://manage.office.com 已禁用”的 Office 365 管理 API
- sparql - 我对 SPARQL 的 CONSTRUCT 有疑问
- javascript - 如何使用 Puppeteer 在元素上绘制边界框
- android - Android Things,如何捕获进程终止
- c++ - 非平凡可复制类型的 C++ 值表示
- sql - 如何在 bigquery 窗口中查找分类异常值/噪声行
- python - pdoc3-ValueError:找不到文件或模块
- python - 如何从字符串创建图像?
- python - Django Rest Framework 嵌套可写字段 mixins drf_writable_nested
- python - 获取所采用的路径,直到 python 中的一行