Programmer
Programmer

Reputation: 687

mockito when method returns null in junit

I have been writing the test cases using the mockito. the below is my code in the test cases.

@RunWith(SpringRunner.class)
public class LoginControllerTest {

    private MockMvc mockMvc;

    @InjectMocks    
    private LoginService loginService;

    @Mock
    private LoginController loginController;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        // Setup Spring test in standalone mode
        mockMvc = MockMvcBuilders.standaloneSetup(loginController).build();

    }

    @Test
    public final void test() throws Exception {

        // Assign
        when(loginService.test()).thenReturn("hello");

        // act
        mockMvc.perform(get("/hello"))
                // Assertion
                .andExpect(status().isOk())
                .andExpect(content().string("Message from service: hello"));
        verify(loginService).test();
    }

    @Test
    public final void usernameInvalidAndPassword() throws Exception {

        User userData = new User();
        userData.setUserName("[email protected]");
        userData.setPassword("Passw0rd");


        User userDataNew = new User();
        userDataNew.setUserName("[email protected]");
        userDataNew.setPassword("Passw0rd");


        JSONObject requestBody = new JSONObject();

        requestBody.put("userName", "[email protected]");
        requestBody.put("password", "Passw0rd");

        JSONObject responseBody = new JSONObject();

        responseBody.put("status_code", "200");
        responseBody.put("message", "ok");

        // Assign
        when(loginService.saveUser(userData)).thenReturn(userDataNew);

        // act
        mockMvc.perform(get("/login")
                .param("userName", "[email protected]")
                .param("password", "Passw0rd"))
                // Assertion
                .andExpect(status().isOk()).andExpect(content().json(responseBody.toString())).andDo(print());
    }

For the first test case its working fine but for the second test it is returning null always. Can anyone please help? Thanks in advance

Upvotes: 3

Views: 1700

Answers (2)

Maciej Kowalski
Maciej Kowalski

Reputation: 26502

In my opinion you have to either:

1) Introduce equals method based on username and password as the User object created inside the method under test is a different instance than the one you create and use in the test.

2) Use a wildcard in your set-up:

when(loginService.saveUser(Mockito.any(User.class))).thenReturn(userDataNew);

Upvotes: 0

Plog
Plog

Reputation: 9622

You have the annotations the wrong way round on your LoginController and LoginService. You are testing the controller so you don't want to mock it, and you are stubbing methods on your service so this needs to be a mock:

 @Mock  
 private LoginService loginService;

 @InjectMocks
 private LoginController loginController;

Upvotes: 1

Related Questions