2017-03-16 46 views
0

我正在測試一個使用其下的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什麼是在春季啓動有用。

+2

的問題是你的代碼。從你的測試中刪除'@InjectMocks'和'MockitoAnnotations.initMocks(this);'。當使用'@ MockBean'時,Spring Boot會爲您提供所有幫助......您基本上正在使用當前的設置與之對抗。 –

+0

@ M.Deinum它已經爲我工作。謝謝。但是,如果我同時使用MockBean和Mock,應該如何在場景中使用'MockitoAnnotations.initMocks(this);'。 –

+0

你不應該那樣使用任何一個,但不要混合,因爲這會導致你遇到問題。另外,如果您要自己替換bean實例中的變量,那麼在測試之後,您還必須刷新應用程序上下文。 –

回答

2

M.Deinum在評論中指出你正確的方向。

也許你想給有關嘲諷和間諜春天文檔測試的讀取 - 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

相關問題