java - mockito 中的 anyString() 抛出参数匹配器的无效使用

标签 java eclipse mockito

我正在使用 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/

相关文章:

eclipse - 如何在 Talend Open Studio 中添加 Maven 依赖项

eclipse - 使用多个 Git 帐户

c++ - Linux、Eclipse CDT 以 su 运行

java - 使用 PowerMockito 模拟内部类中的 final方法

java - 在 Mockito 中获取 NullpointerException

java - 从队列中提供 Java Applet 服务?

java - `Thread.sleep` 与 Project Loom for Java 中的虚拟线程(纤程)不同吗

java - 使用 Mockito @Spy 注释时未调用 @PostConstruct

Java 接口(interface)和类型多态性,一种实现与扩展

c# - 随机角度发生器