Search code examples
javajunitmockitojunit-jupiter

How to test a utility method that returns a new instance using Jupiter in Java?


I have a something like this one:

class User {
    String name;
}

class Contacts {
    User getUser() {
        return new User();
    }
}

I do it this way so that in my test I can mock the method like:

@ExtendWith(MockitoExtension.class)
class ContactsTest {
    @Spy
    private Contacts sut;

    @Mock
    private User user;

    @Test
    void testSomething() {
        doReturn(user).when(sut).getUser();
    }

    @Test
    void testGetUser() {
        // verify(new User(), times(1));
        // verify(user, times(1));
    }
}

How could I test testGetUser?

The only two ideas I had which are commented above gave me these errors:

For the first one:

org.mockito.exceptions.misusing.NotAMockException: 
Argument passed to verify() is of type User and is not a mock!
Make sure you place the parenthesis correctly!
See the examples of correct verifications:
    verify(mock).someMethod();
    verify(mock, times(10)).someMethod();
    verify(mock, atLeastOnce()).someMethod();

For the second one

org.mockito.exceptions.misusing.UnfinishedVerificationException: 
Missing method call for verify(mock) here:

Solution

  • First of all, since your unit under test is the Contacts class there is no need to spy on it and mock its behavior as this is the class you need to test. So, I would go ahead and remove that.

    Now regarding your question, what you need to test is the actual outcome of the getUser, so the simplest of all tests would be to invoke the method on an instance of Contacts and assert that the returned result is a non-null instance of a User object.

    If you really want to test that the constructor of the User class gets called, you will need to actually mock that call using either PowerMock (which is advise against and most likely does not even work with JUnit5) or use mockito-inline.

    Once this is done you would be able to return a mocked User instance from the constructor call which you can then run assertions on.