我正在使用 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();
}
谁能解释为什么我会收到错误以及我可以采取什么措施来解决它?
最佳答案
userRepositoryImplementation.getUserByUsername(anyString());
这不是 anyString()
的正确用法。
它可用于 stub 或验证。但不适用于实际调用方法。
来自 documentation :
Allow flexible verification or stubbing.
如果在测试运行时你想要一个随机字符串尝试使用RandomStringUtils或任何其他类似的库。
userRepositoryImplementation.getUserByUsername(RandomStringUtils.random(length));
关于java - mockito 中的 anyString() 抛出参数匹配器的无效使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37408192/