【问题标题】:Mockito when().thenReturn doesn't workMockito when().thenReturn 不起作用
【发布时间】:2013-09-24 14:47:34
【问题描述】:

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

}

【问题讨论】:

    标签: java spring spring-mvc mocking mockito


    【解决方案1】:

    问题是您没有正确使用post() 方法。 See the javadoc here.

    在你传递的参数中

    post("/create", wrapper, result)
    

    wrapperresult 用作 url 变量,而不是 create 方法的方法参数。您不能以这种方式模拟 BindingResult。在 imo 上模拟它实际上非常困难,从长远来看可能不值得。如果有的话,您应该使用有效或无效的命令对象进行测试。

    【讨论】:

    • @qiGuar 正如我在回答中所说,我认为没有一种简单且值得的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 2017-07-21
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多