N.Rajal
N.Rajal

Reputation: 175

Can't use when().thenReturn() for a mockbean, getting NPE with doReturn().when() also

I have a junit test class that mocks couple of classes dependencies using @MockBean annotation.

@ExtendWith(MockitoExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
@ActiveProfiles("test")
public class AuthServiceTest {

    @InjectMocks private AuthService authService;

    @MockBean UserService userService;
    @MockBean ...... // other mocks


    @Test
    public void testVerifyAuth() {
          User user = new User();
          // setting user params
          Mockito.lenient().when(userService.createUser(anyString(), anyLong(), anyString(), any(Integer.class)....).thenReturn(user));

    }

}

The userService stubbing is working fine for one of the UserService methods but for other one (createUser), it fails and getting this error:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: User cannot be returned by toString() toString() should return String *** If you're unsure why you're getting above error read on. Due to the nature of the syntax above problem might occur because:

  1. This exception might occur in wrongly written multi-threaded tests. Please refer to Mockito FAQ on limitations of concurrency testing.
  2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
    • with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

It suggests to use doReturn().when() as due to some reason (maybe stubbing was not done properly), it's not able to find this stubbing. I tried to use this one too, but during debug, when this stubbing is actually called in main UserService.class, then the user object is returned as null instead of the object I was trying to create.

Is there anything I've been missing here?

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:

All the other dependencies are working fine as expected

Upvotes: 1

Views: 1467

Answers (1)

Parth Manaktala
Parth Manaktala

Reputation: 1178

As per the error it says you are returning the wrong type from the mocked method.

The method userService.createUser should return a type as String where as you are trying to return the type as User. Hence the error

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: User cannot be returned by toString() toString() should return String ***

What is the return type of your createUser method? The mock should return the same. Assuming create user as

String createUser(String name, Long age){
    //Database operations etc.
    return "Success";
}

The mock should be

Mockito.when(serviceClassMock.createUser(anyString(), anyLong()).thenRetun("Success");

Also, here you can get NPE as well if either the name or age is NULL. Either make sure that no parameter of the mocked method is null, or if its expected to have null then use Mockito.nullable(String.class) and so on.

Upvotes: 1

Related Questions