简体   繁体   中英

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

I am using eclipse to run some unit tests on a class and I am using Mockito so I don't have to connect to the database. I have used anyString() in other tests which works but it isn't working in this test. If I change it from anyString() to "" the error disappears and the test passes.

My test is:

@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();

}

Can anyone explain why I am getting the error and what I can do to resolve it?

You can use Matchers , like anyString() for mocking up (stubbing) an object. Ie inside a when() invocation. Your invocation is an actual invocation:

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

So that's right: for testing you have to add some real input, like "" , "salala" or null .

userRepositoryImplementation.getUserByUsername(anyString());

This is not the right use of anyString() . It can be used for stubbing or for verifying. But not for actual call of method. From documentation :

Allow flexible verification or stubbing.

If you want a random string when test is running try to use RandomStringUtils or any other similar library.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM