简体   繁体   中英

How do I know if Mock in Spring boot is being used or not?

I am testing a service class which uses a Dao layer under it.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class AppServiceTest {

    @Autowired
    @InjectMocks
    private AppService appService;

    private AppConfig appConfig = new AppConfig(), appConfigOut = new AppConfig();

    @MockBean //This statement is under inspection in the problem
    private AppDao appDao;

    @Before
    public void setUp() throws Exception {
       String appKey = "jsadf87bdfys78fsd6f0s7f8as6sd";
       appConfig.setAppKey(appKey);

       appConfigOut.setAppKey(appKey);


       appConfigOut.setRequestPerMinute(null);
       appConfigOut.setRequestDate(DateTime.now());
       MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testFetchAppConfigValidParam() throws Exception {
        when(appDao.fetchAppConfig(appConfig)).thenReturn(appConfigOut);
        assertThat(appService.fetchAppConfig(appConfig)).isEqualToComparingFieldByField(appConfigOut);
    }

In the above program when I write @MockBean , the test throws a NullPointerException, but when I write @Mock the test executes successfully. I think the appDao being called is the actual one defined in appService and accessing the database. This is because the time taken by the test is around 200ms and usual test cases for other applications is 60ms-100ms. But I am not sure because other cases where DAO really access data takes 400ms to 500ms.

How do I know mock is actually working and when appService calls the appDao method from inside it is actually the mock. Is there any programmatical way to verify this.

PS If @Mock works in this scenario what is @MockBean is useful for in spring boot.

M.Deinum is pointing you in the correct direction in the comment.

Maybe you want to give the spring documentation about Mocking and Spying in tests a read - https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-mocking-beans

But to answer you question - you can use MockingDetails to tell if an object is a mock.

MockingDetails mockingDetails = org.mockito.Mockito.mockingDetails(appDao)

boolean appDaoIsMock = mockingDetails.isMock()

( https://stackoverflow.com/a/15138628/5371736 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM