测试时:“DataBinder已经使用ConversionService初始化”,但在Tomcat中可以

时间:2015-10-26 11:51:48

标签: junit4 spring-4

我正在尝试编写Junit / MockMVC测试,但有疯狂的异常。

Caused by: java.lang.IllegalStateException: DataBinder is already initialized with ConversionService.

奇怪,但一切都适用于Tomcat。

这是我的测试用例:

@Test
@WithMockUser(roles = {"capacity-user"})
public void testSaveNewLocalIP() throws Exception {
    DslLnsLocalIp lip = new DslLnsLocalIp();
    MockMvc mockMvcController = MockMvcBuilders.standaloneSetup(new DSLCapacity()).build();
    mockMvcController.perform(
            post("/dashboard/dsl-capacity/newLocalIP")
              .contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8)
              .content(IntegrationTestUtil
              .convertObjectToJsonBytes(lip)))
            .andExpect(status().isOk());
}

并且我们的控制器排除了不相关的方法。

@Controller
@RequestMapping("/dashboard/dsl-capacity")
public class DSLCapacity {
  @Autowired
  private DSLCapacityDao dcDao;

  @Autowired
  private ConversionService conversionService;

  @InitBinder
  protected void initBinder(WebDataBinder binder)
  {
    binder.setConversionService(conversionService);
    if(binder.getTarget() instanceof DslLns)
    {
        binder.setValidator(new LNSValidator());
    }
    if(binder.getTarget() instanceof DslLnsLocalIp)
    {
        binder.setValidator(new LnsLocalIpValidator());
    }
  }
@RequestMapping(value = "/newLocalIP", method = { RequestMethod.PUT, RequestMethod.POST })
public String saveNewLocalIP(@ModelAttribute("newLocalIP") @Valid DslLnsLocalIp localIP, BindingResult result, Model model)
{
    try
    {
        if(!result.hasErrors()) dcDao.createLocalIP(localIP);
    }
    catch (AlreadyExists e)
    {
        result.rejectValue("ip", null, "That local IP already exists");
    }
    if(result.hasErrors())
    {
        model.addAttribute("localIP", localIP);
        // ControllerUtils.addError(model,"Please correct the errors below and try again");
        return getNewLocalIP(model);
    }
    return "redirect:/dashboard/dsl-capacity/";
}

请告诉我是否有其他事情可以帮助您解决问题。

1 个答案:

答案 0 :(得分:2)

试试这个!

    @InitBinder
    protected void initBinder(WebDataBinder binder)
    {
            if(binder.getConversionService() == null)
                    binder.setConversionService(conversionService);
            if(binder.getTarget() instanceof DslLns)
            {
                    binder.setValidator(new LNSValidator());
            }
            if(binder.getTarget() instanceof DslLnsLocalIp)
            {
                    binder.setValidator(new LnsLocalIpValidator());
            }
    }