测试时:"DataBinder is already initialized with ConversionService",但在Tomcat中没问题

When testing: "DataBinder is already initialized with ConversionService",but all right in Tomcat

我正在尝试编写 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/";
}

请让我知道是否有其他方法可以帮助您解决问题。

试试这个!

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