Code Snippet

Just another Code Snippet site

[Java] Controller & Junits

Controller :

@Controller
@RequestMapping("public")
public class SearchController {

    @RequestMapping(value = { "search.html" }, method = RequestMethod.POST)
    public String performSearch(ModelMap model, HttpServletRequest request, BindingResult bindingResult) {

         // Do something with validation
         bindingResult.addError(...);

         // Add stuff to model
         model.addAttribute("result", new ArrayList<?>());

         return "search";
    }

}

JUnit :

import static org.mockito.Mockito.mock;

public class AdvancedSearchControllerTest {

    @Test
    public void testSearchMethod() {
        SearchController controller = new SearchController ();

        ModelMap model = new ModelMap();        
        HttpServletRequest request = mock(HttpServletRequest.class);        
        MapBindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), "OBJ_NAME");

        String viewName = controller.performSearch(model, request, bindingResult);

        Assert.assertTrue(model.containsAttribute("result"));
        Assert.assertEquals(1, bindingResult.getErrorCount());
        // TODO ...
    }

}

Mock Authentication :

import static org.mockito.Mockito.mock;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;

public class AdvancedSearchControllerTest {

    @Test
    public void testWithAuthentication() {
        // Mock Authentication & user
        final Authentication auth = mock(Authentication.class);
        final User user = mock(User.class);

        // Define values
        when(auth.getPrincipal()).thenReturn(user);
        when(user.getUsername()).thenReturn("JohnDoe");
        when(user.getAuthorities()).thenReturn(AuthorityUtils.createAuthorityList("ANONYMOUS"));

        // Set authentication in SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(auth);

        // Call controller method
        // ...
    }

}

,


One thought on “[Java] Controller & Junits

Leave a Reply to Olivier Cancel reply

Your email address will not be published. Required fields are marked *