2

I wrote this controller method:

  @RequestMapping("/submitFormAdd")
        public ModelAndView submitFormAdd(
                Model model,
                @ModelAttribute("myCandidate") @Valid Candidate myCandidate,
                BindingResult result,
                RedirectAttributes redirectAttributes) {
            if (result.hasErrors()) {
                return new ModelAndView("candidateDetailsAdd");
            }

            myCandidate.setDate(new Date());
            candidateService.add(myCandidate);

            redirectAttributes.addAttribute("message", "added Correctly at "+ new Date() );
            redirectAttributes.addAttribute("id", myCandidate.getId());
            ModelAndView modelAndView = new ModelAndView(
                    "redirect:loadCandidateById");
            return modelAndView;
        }

UPDATE

myCandidate instantiants so:

@ModelAttribute(value = "myCandidate")
    public Candidate loadCandidateById(
            @RequestParam(required = false) Integer candidateId) {
        if (candidateId != null)
            return candidateService.findById(candidateId);
        return null;
    }

What way can I test that this method gets Candidate ?

I use MockMvc.

1 Answers1

0

You cannot test specifically that the method will receive the Candidate argument. Your options are to either send bad request data and therefore make Spring unable to correctly instantiate it and return a 400 error (but that can happen for other reasons). Or send correct data and receive what you normally expect.

Note that you shouldn't be testing Spring functionality. When you use a 3rd party framework, you assume that it has been tested properly, especially one like Spring.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • @user2740224 If that's how you are getting it then I would test that particular method. Spring will correctly resolve it as an argument for your handler method. Trust it. – Sotirios Delimanolis Oct 03 '13 at 14:58
  • I can test that loadCandidateById method will invoke before submitFormAdd method ? –  Oct 03 '13 at 15:05
  • @user2740224 No, you can test them individually. – Sotirios Delimanolis Oct 03 '13 at 15:07
  • maybe exist way for testing order of these method invocation? –  Oct 03 '13 at 15:19
  • @user2740224 Not through `MockMvc`. Those tests possibly exist in the Spring unit tests. You don't need to unit test that, it's outside the scope of your code. Integration testing will show you that it works. – Sotirios Delimanolis Oct 03 '13 at 15:21
  • Ok. Maybe you can get me link for researching ? –  Oct 03 '13 at 15:27
  • @user Sure. The spring documentation. First start with the [chapter on Testing](http://docs.spring.io/spring/docs/3.2.4.RELEASE/spring-framework-reference/html/testing.html), which includes [Spring MVC testing](http://docs.spring.io/spring/docs/3.2.4.RELEASE/spring-framework-reference/html/testing.html#spring-mvc-test-framework). – Sotirios Delimanolis Oct 03 '13 at 15:40