I found that Mockbean is work the test main thread, but not work in the new thread call, following is my demo code. call the mock first time in new thread is work, but when call the demoService in second times, it return null (mock not work)

Reference Jar Version mockito-core 4.11.0 JDK1.8 Junit4 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());

}

}

Uploading demo.zip…