2016-05-24 46 views
0

我正在使用eclipse在類上運行一些單元測試,我正在使用Mockito,因此我不必連接到數據庫。我在其他測試中使用了anyString(),但它在這個測試中不起作用。如果我將它從anyString()更改爲「」,則錯誤消失並且測試通過。mockito中的anyString()拋出參數匹配器的無效使用

我的測試是:

@Test 
public void test_GetUserByUsername_CallsCreateEntityManager_WhenAddUserMethodIsCalled() { 

    //Arrange 
    EntityManagerFactory mockEntityManagerFactory = mock(EntityManagerFactory.class); 
    EntityManager mockEntityManager= mock(EntityManager.class); 
    UserRepositoryImplementation userRepositoryImplementation = new UserRepositoryImplementation(); 
    userRepositoryImplementation.setEntityManagerFactory(mockEntityManagerFactory); 

    when(mockEntityManagerFactory.createEntityManager()).thenReturn(mockEntityManager); 


    //Act 
    userRepositoryImplementation.getUserByUsername(anyString()); 

    //Assert 
    verify(mockEntityManagerFactory, times(1)).createEntityManager(); 

} 

誰能解釋爲什麼我收到錯誤,我能做些什麼來解決它?

回答

1
userRepositoryImplementation.getUserByUsername(anyString()); 

這不正確的使用anyString()。 它可以用於存根或驗證。但不適用於實際的方法調用。 從documentation

允許靈活的驗證或存根。

如果您想在測試運行時使用隨機字符串,請嘗試使用RandomStringUtils或任何其他類似的庫。

userRepositoryImplementation.getUserByUsername(RandomStringUtils.random(length)); 
1

您可以使用Matchers,如anyString()嘲笑(樁)一個對象。即在when()調用中。您的調用是一個實際的調用:

//Act 
userRepositoryImplementation.getUserByUsername(anyString()); 

所以這是正確的:測試你必須添加一些真正的輸入,像"""salala"null

相關問題