我发现Mockbean可以在测试主线程中工作,但不能在新线程调用中工作,下面是我的演示代码。在新线程中第一次调用mock是工作的,但是当第二次调用demoService时,它返回null(mock不工作)
参考Jar版本mockito-core 4.11.0 JDK1.8 Junit 4 SpringBoot:1.5.22.RELEASE
/***
* demo test case for find why mockito mock not work in new thread
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class DemoApplicationTests {
@MockBean
protected DemoService demoService;
/**
* call the mock in main thread, the mock all work
*/
@Test
public void testNormalCase_work() {
DemoServiceMock.mockdoSomething(demoService);
String result = demoService.doSomething("324234");
System.out.println("return: " + result);
String result2 = demoService.doSomething("324234");
System.out.println("return2: " + result);
}
/***
* call the mock in new thread
* When call the demoService in second times, it return null (mock not work)
*/
@Test
public void testInNewThread_notWork() {
DemoServiceMock.mockdoSomething(demoService);
Thread t = new Thread(new Runnable() {
public void run() {
//for the first time call, the mock is work
String result = demoService.doSomething("324234");
System.out.println("return in thread: " + result);
//for this second time call in new thread, the mock not work and return null
String result2 = demoService.doSomething("324234");
System.out.println("return2 in thread: " + result2);
}
});
t.start();
}
}
public class DemoServiceMock {
public static void mockdoSomething(DemoService demoService){
Mockito.doReturn("mockReturnValue").when(demoService).doSomething(any());
}
}
我发现Mockbean可以在测试主线程中工作,但不能在新线程调用中工作,下面是我的演示代码。在新线程中第一次调用mock是工作的,但是当第二次调用demoService时,它返回null(mock不工作)
1条答案
按热度按时间b4qexyjb1#
我无法在本地重现您的行为(但使用JUnit 5、Sping Boot 2和JDK 11)。然而,这是非常可疑的,你不等待你的线程完成。多次运行测试可能会成功或失败,具体取决于语句的执行顺序。
当第二次调用被发出时,测试运行器可能已经关闭并注销了所有stubbing调用。race condition的一个典型例子
等待线程完成可能会“解决”你的问题:
PS帮你自己一个忙,停止使用过时的/生命周期结束的软件和库。有JUnit 5、Sping Boot 3和JDK 17。所有后者仍然获得更新和安全修复,而您的版本仍然未维护且易受攻击。