0

我正在尝试为我的弹簧控制器编写测试并遇到问题。以下代码总是返回,redirect:/welcome尽管我有when(result.hasErrors()).thenReturn(true);应该返回add的。可能是我做错了什么。请帮我解决这个问题。

控制器

@Controller
public class SpringController {

@Autowired
private UserService userService;

@Autowired
private CorrectValidator correctValidator;

@Autowired
private ExistValidator existValidator;

@Autowired
private Unwrapper unwrapper;

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create (Wrapper wrapper,
                      BindingResult result)
        throws ParseException {
        correctValidator.validate(wrapper, result);
        existValidator.validate(wrapper, result);
        if (result.hasErrors()) {
            return "add";
        }
        userService.create(unwrapper.unwrap(wrapper));
        return "redirect:/welcome";
    }
}

测试

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring-servlet.xml"})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class})
public class ControllerTest {

@InjectMocks
private SpringController controller;

@Mock
private Wrapper wrapper;   

@Mock
private BindingResult result;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    mockMvc = standaloneSetup(controller)
            .setSingleView(mockView)
            .build();
}

    @Test
    public void testCreateBad() throws Exception {
        when(result.hasErrors()).thenReturn(true);

        mockMvc.perform(post("/create", wrapper, result))
                .andExpect(status().isOk())
                .andExpect(view().name("add"));
    }

}
4

1 回答 1

2

The problem is you are not using the post() method correctly. See the javadoc here.

In the arguments you pass

post("/create", wrapper, result)

wrapper and result are used as url variables, not as method arguments for your create method. You cannot mock the BindingResult this way. It's actually extremely hard imo to mock it and probably not worth it in the long run. If anything you should test with command objects that will or won't be valid.

于 2013-09-24T15:07:30.260 回答