我正在測試一個使用其下的Dao層的服務類。我如何知道是否正在使用Spring引導中的模擬?
@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);
}
在上述程序中,當我寫@MockBean
,測試拋出一個NullPointerException,但是當我寫@Mock
測試成功執行。我認爲appDao被調用的是appService
中定義的實際數據並訪問數據庫。這是因爲測試所用的時間大約爲200ms,而其他應用程序的通常測試用例爲60ms-100ms。但我不確定,因爲DAO真正訪問數據的其他情況需要400毫秒到500毫秒。
我怎麼知道模擬實際上工作,當appService
從裏面調用appDao
方法實際上是模擬。有沒有任何編程方法來驗證這一點。
P.S.如果@Mock
在這種情況下工作@MockBean
什麼是在春季啓動有用。
的問題是你的代碼。從你的測試中刪除'@InjectMocks'和'MockitoAnnotations.initMocks(this);'。當使用'@ MockBean'時,Spring Boot會爲您提供所有幫助......您基本上正在使用當前的設置與之對抗。 –
@ M.Deinum它已經爲我工作。謝謝。但是,如果我同時使用MockBean和Mock,應該如何在場景中使用'MockitoAnnotations.initMocks(this);'。 –
你不應該那樣使用任何一個,但不要混合,因爲這會導致你遇到問題。另外,如果您要自己替換bean實例中的變量,那麼在測試之後,您還必須刷新應用程序上下文。 –