2009-05-18 90 views
13

我正在迁移Spring MVC控制器以使用更新的样式注释,并希望单元测试验证命令对象的控制器方法(请参阅下面的简单示例)。使用注释模仿Spring MVC BindingResult

@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 
    } 

我的问题是我要叫我的单元测试控制器的方法,并提供模拟值,以满足其签名恰当地执行代码,我不能工作,如何嘲笑一个BindingResult。

在老式控制器中,签名只需要一个HttpServletRequest和HttpServletResponse,它们很容易实现,但由于新注释风格的灵活性,必须通过签名传递更多内容。

如何模拟一个单元测试中使用的Spring BindingResult?

回答

15

BindingResult是一个接口,所以你不能简单地通过该接口的一个Springs实现吗?

我没有在我的Spring MVC中的代码使用注释,但是当我想测试验证程序的验证方法,我传递中的BindException的一个实例,然后使用它的assertEquals等

+4

嗨马克, ,这让我在正确的轨道谢谢。使用一个 BindingResult bindingResult = new BeanPropertyBindingResult(command,“command”);并且在我的测试中在模型中粘贴命令对象似乎将我的测试排除在外。 – 2009-05-18 14:23:19

+1

我也是这么做的。 – 2009-05-20 01:23:31

14

返回值你也可以使用像Mockito创建BindingResult的模拟,并传递到你的控制器的方法,即

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); 
} 

这可以给你更多的灵活性和简化了脚手架。