javaspringspring-mvcjunitmockmvc

Spring JUnit testing using mockMvc


I am trying to unit test my rest controller using spring and mockito. Here is my main controller method.

public static final String AUTHENTICATE_USER_URI = "/user/authenticate";

private static final Logger logger = LoggerFactory.getLogger(RestfulController.class);

@Autowired
User user;

@Autowired
AuthenticationService authService;

@CrossOrigin
@RequestMapping(value = (AUTHENTICATE_USER_URI), method = RequestMethod.GET, produces = "application/json")
private User getUserAuthenticationDetails(
        @RequestParam("name") String name,
        @RequestParam("password") String password) throws NamingException,
        AuthenticationException {
    boolean isAuth = true;

    // checks user credentials
    isAuth = authService.isAuthenticated(name, password);

    if (isAuth) {
        logger.debug("User is authenticated");
        user = authService.getUserDetails(user, name);
        // // persistUserInDB(user);
        return user;
    } else {
        logger.debug("User is not authenticated");
        return null;
    }
}

Here is my JUnit test:

@RunWith(MockitoJUnitRunner.class)
public class RestfulControllerTest {
        
    private static final String AUTHENTICATE_USER_TEST_URI = "http://localhost:8086/LDAPAuthenticationApp/user/authenticate";

    private MockMvc mockmvc;
    
    @Mock
    private AuthenticationService authService;
    
    @Before
    public void setUp() {
        mockmvc = MockMvcBuilders.standaloneSetup(new RestfulController())
            .setHandlerExceptionResolvers(exceptionResolver())
            .setMessageConverters(messageConverters())
            .build();
    }

    private MappingJackson2HttpMessageConverter messageConverters(){
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        return converter;
    }
        
    private HandlerExceptionResolver exceptionResolver() {
        // exceptionResolver implementation here
    }

    // success test case
    @Test
    public void testGetUserAuthenticationDetails() throws Exception {
        String[] name={"user1","user2","user3"};
        String value="test pass";
        when(authService.isAuthenticated(any(String.class), any(String.class))).thenReturn(true);
        when(authService.getUserDetails(any(User.class),any(String.class))).thenReturn(any(User.class));
        for(int i=0;i<3;i++){
             mockmvc.perform(get(AUTHENTICATE_USER_TEST_URI).param("name", name[i]).param("password", value))
              .andDo(print()).andExpect(MockMvcResultMatchers.status().isOk())
              .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON));
    }
    verify(authService, atMost(3)).isAuthenticated(any(String.class), any(String.class));
}

In the output response, test is failing as it is getting 404 error but it is expecting a 200 success code. What could I be doing wrong as I believe I have setup the standalone configuration correctly. Why URI is not getting mapped to method properly? Please note it is working correctly for same URI from frontend of the application. Here is the full URI for proper 200 response which I have tested using Postman tool for chrome:

http://localhost:8086/LDAPAuthenticationApp/user/authenticate?name=amol84&password=testpass


Solution

  • Maybe you should try with this url:

    private static final String AUTHENTICATE_USER_TEST_URI = "/user/authenticate";