unit-testing - 使用注释时模拟 Spring MVC BindingResult

标签 unit-testing spring-mvc mocking

我正在迁移 Spring MVC Controller 以使用较新的样式注释,并希望对验证命令对象的 Controller 方法进行单元测试(请参见下面的简单示例)。

 @RequestMapping(method = RequestMethod.POST)
public String doThing(Command command, BindingResult result,
                    HttpServletRequest request, HttpServletResponse response,
                    Map<String, Object> model){ 
    ThingValidator validator = new ThingValidator();
    validator.validate(command, result);
... other logic here
    }

我的问题是我必须在我的单元测试中调用 Controller 的方法,并提供模拟值以满足其签名以正确执行代码,而且我无法弄清楚如何模拟 BindingResult。

在旧样式的 Controller 中,签名只是简单地采用了 HttpServletRequest 和 HttpServletResponse,它们很容易被模拟,但是由于新注释样式的灵活性,必须通过签名传递更多内容。

如何模拟 Spring BindingResult 以用于单元测试?

最佳答案

你也可以使用类似 Mockito 的东西创建 BindingResult 的模拟并将其传递给您的 Controller 方法,即

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verifyZeroInteractions;

@Test
public void createDoesNotCreateAnythingWhenTheBindingResultHasErrors() {
    // Given
    SomeDomainDTO dto = new SomeDomainDTO();
    ModelAndView mv = new ModelAndView();

    BindingResult result = mock(BindingResult.class);
    when(result.hasErrors()).thenReturn(true);

    // When
    controller.create(dto, result, mv);

    // Then
    verifyZeroInteractions(lockAccessor);
}

这可以为您提供更大的灵活性并简化脚手架。

关于unit-testing - 使用注释时模拟 Spring MVC BindingResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/877423/

相关文章:

c# - 如何使现有的公共(public) API 可供使用它的外部程序员测试?

java - myBatis xml 映射器文件管理器与 Java 接口(interface)一起使用 - 动态 SQL 查询

c# - 如何模拟在 using() block 中实例化的对象

reactjs - 用 Jest 模拟 react-beautiful-dnd

ios - 如何使用 XCTAssertThrowsSpecific

unit-testing - 单元测试在游戏编程中可行吗?

python:在单元测试中测试特定功能?

java - Spring MVC @RequestMapping 对于类级别和方法级别不起作用

java - spring mvc中资源不可用问题

unit-testing - Windows Store 应用程序的单元测试库中选择的模拟框架是什么?