簡體   English   中英

Mockito中的anyString()拋出參數匹配器的無效使用

[英]anyString() in mockito is throwing an invalid use of argument matchers

我正在使用eclipse在類上運行某些單元測試,並且正在使用Mockito,因此不必連接到數據庫。 我在其他可以使用的測試中使用了anyString(),但在該測試中不起作用。 如果我將其從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();

}

誰能解釋我為什么會收到錯誤以及如何解決該錯誤?

您可以使用Matchers ,像anyString()的嘲諷起來(存根)的對象。 即在when()調用內。 您的調用是實際的調用:

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

沒錯:為了進行測試,您必須添加一些實際輸入,例如"""salala"null

userRepositoryImplementation.getUserByUsername(anyString());

這不是對anyString()的正確使用。 它可以用於存根或驗證。 但不用於方法的實際調用。 文檔

允許靈活的驗證或存根。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM