我正在尝试为我的弹簧控制器编写测试并遇到问题。以下代码总是返回,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"));
}
}