2013-09-24 44 views
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")); 
    } 

} 

回答

2

問題是你沒有正確使用方法post()See the javadoc here

在參數傳遞

post("/create", wrapper, result) 

wrapperresult作爲url的變量,而不是你的create方式方法的參數。你不能以這種方式嘲笑BindingResult。它實際上是非常困難的嘲笑它,並可能在長遠看來不值得。如果有什麼需要測試的命令對象將會或不會有效。

+0

那麼我該如何正確地將結果傳遞給控制器​​呢? – qiGuar

+0

@qiGuar正如我在我的回答中所述,我不認爲有一種簡單而有價值的方式來做到這一點。 –

相關問題