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.