0

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.

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

4

1 回答 1

2

M.Deinum 在评论中为您指明了正确的方向。

也许您想阅读有关在测试中模拟和监视的 Spring 文档 - https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features -testing-spring-boot-applications-mocking-beans

但是要回答您的问题-您可以使用MockingDetails来判断对象是否是模拟对象。

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

boolean appDaoIsMock = mockingDetails.isMock()

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

于 2017-03-16T07:37:53.563 回答