spring不会使用@jsoncreator进行解析

63lcw9qa  于 2021-07-22  发布在  Java
关注(0)|答案(0)|浏览(209)

我有以下几点 enum :

public enum Strategy {
  STRAT_A,
  STRAT_B,
  STRAT_C;

  @JsonCreator
  public static Strategy creator(final String strategy) {
    return Strategy.valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, strategyId));
  }
}

这是在 StrategyRequest 班级:

public class StrategyRequest {
  @NotNull
  private Strategy strategy;

  private String name;

  private BigDecimal value;
}

控制器:

public class Controller {
  @GetMapping(value = "/strategy")
  StrategyResponse getStrategy(@Valid StrategyRequest request){...};
}

我创建了以下测试:

class ControllerTest { 
  private MockMvc mockMvc;
  private ObjectMapper objectMapper;

  @BeforeEach
  void setUp() {
    mockMvc = MockMvcBuilders.standaloneSetup(new Controller()).setCustomHandlerMapping(ApiRequestMappingHandler::new).build();
    objectMapper = new ObjectMapper();
  }

  @Test
  void getStrategyTest() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/strategy").queryParam("strategyId", "stratA"))
        .andExpect(MockMvcResultMatchers.status().isOk());
  }
}

测试时,我得到以下错误:

[main] WARN org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'strategyRequest' on field 'strategy': rejected value [stratA]; codes [typeMismatch.strategyRequest.strategy,typeMismatch.strategy,typeMismatch.strategy.Strategy,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [strategyRequest.strategy,strategy]; arguments []; default message [strategy]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'strategy.Strategy' for property 'strategy'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.validation.constraints.NotNull strategy.Strategy] for value 'stratA'; nested exception is java.lang.IllegalArgumentException: No enum constant strategy.Strategy.stratA]]

我发现造物主从来没用过。。。它只在测试时发生。正常功能运作良好

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题