junit4 - PowerMock 没有存根正确的方法
问题描述
我正面临一个奇怪的 PowerMock 问题。让我更详细地解释一下。
我的代码:
@Service
public class TestMe {
@Autowired
private ClassA a;
@Autowired
private ClassB b;
@Autowired
private ClassStatic staticClass;
public void init(){
List<String> nameList = returnNames(); // Line#1
// Work with names
List<String> placeList = returnPlaces(); // Line#2
// Work with places
}
public List<String> returnNames(){
// Code to return list of names
}
public List<String> returnPlaces(){
// Code to return list of places
}
}
我的测试班
@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassStatic.class})
public class TestMeTest {
@Mock
private ClassA aMock;
@Mock
private ClassB bMock;
@InjectMocks
private TestMe testMeMock;
@Test
public void testInit(){
List<String> listNames = ... // some list of names
List<String> listPlaces = ... // some list of places
when(testMeMock.returnNames()).thenReturn(listNames);
// listPlaces gets returned in Line#1 shown in the main code.
when(testMeMock.returnPlaces()).thenReturn(listPlaces);
testMeMock.init();
}
}
因此,正如您在第 1 行中看到的那样,我得到的是 listPlaces 而不是 listNames。如果我重新安排 when 调用,那么我会在 Line#2 处得到 listNames 而不是 listPlaces。
为什么 PowerMock 与方法混淆?或者在使用 PowerMock 时我还缺少其他一些东西。
解决方案
我可以通过使用 thenReturn 两次来解决这个问题,如下所示
when(testMeMock.returnNames()).thenReturn(listNames).thenReturn(listPlaces);
// Removed the returnPlaces() call
// when(testMeMock.returnPlaces()).thenReturn(listPlaces);
testMeMock.init();
但是为什么 PowerMock 不能区分两个不同的方法调用 returnNames() 和 returnPlaces()?
推荐阅读
- internet-explorer - 网络浏览器控制 | 多个 iFrame 嵌入式 YTPLAYER 视频 | 只有第一个 Vid 功能
- javascript - 用 JavaScript 为作品集制作 WebApp。头像不动
- html - 即使内容无法在浏览器大小范围内显示,我的 HTML 网页也不显示滚动条
- javascript - 加载全新图块时的 Mapbox 事件
- sql - Oracle 简单列表结果以逗号分隔的列表与引号?
- python - launch.json - 默认情况下不同程序的不同参数?
- java - 使用 Tycho 构建示例项目会出现错误
- filter - 如何使用 Vega-lite 过滤字符串前缀
- php - 使用 Sed 和 grep 作为日志文件
- c++ - 如何定义二维数组的向量?