0
我想爲我的彈簧控制器編寫測試並遇到問題。以下代碼總是返回redirect:/welcome
,但我有when(result.hasErrors()).thenReturn(true);
,應該返回add
。可能是我做錯了什麼。請幫我解決這個問題。Mockito when()。然後返回不起作用
控制器
@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"));
}
}
那麼我該如何正確地將結果傳遞給控制器呢? – qiGuar
@qiGuar正如我在我的回答中所述,我不認爲有一種簡單而有價值的方式來做到這一點。 –