java - 无法在单元测试中使用自定义 Spring 转换器

标签 java spring spring-boot spring-mvc

我正在使用简单的转换器将字符串转换为枚举。这是自定义转换器:

@Component
public class SessionStateConverter implements Converter<String, UserSessionState> {

    @Override
    public UserSessionState convert(String source) {
        try {
            return UserSessionState.valueOf(source.toUpperCase());
        } catch (Exception e) {
            LOG.debug(String.format("Invalid UserSessionState value was provided: %s", source), e);

            return null;
        }
    }
}

目前,我在休息 Controller 中使用 UserSessionState 作为 PathVariable 。实现按预期进行。但是,当我尝试对其余 Controller 进行单元测试时,似乎转换不起作用并且没有命中 Controller 方法。

@RunWith(MockitoJUnitRunner.class)
public class MyTest {
private MockMvc mockMvc;

@Mock
private FormattingConversionService conversionService;

@InjectMocks
private MynController controller;


@Before
public void setup() {
    conversionService.addConverter(new SessionStateConverter());
    mockMvc = MockMvcBuilders.standaloneSetup(controller).setConversionService(conversionService).build();
}


 @Test
public void testSetLoginUserState() throws Exception {
    mockMvc.perform(post("/api/user/login"));
}

}

在 Debug模式下,我收到以下错误:

nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'rest.api.UserSessionState': no matching editors or conversion strategy found

在我看来,转换服务的模拟不起作用。 有什么想法吗?

最佳答案

如果有人使用工具org.springframework.core.convert.converter.Converter<IN,OUT>如果您在使用mockMvc时遇到类似错误,请按照以下方法操作。

@Autowired
  YourConverter yourConverter;

  /** Basic initialisation before unit test fires. */
  @Before
  public void setUp() {
    FormattingConversionService formattingConversionService=new FormattingConversionService();
    formattingConversionService.addConverter(yourConverter); //Here

    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.standaloneSetup(getController())
        .setConversionService(formattingConversionService) // Add it to mockito
        .build();
  }

关于java - 无法在单元测试中使用自定义 Spring 转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54023341/

相关文章:

java - 使用cascade={CascadeType.TYPE_NAME}的目的是什么

JSON解析错误: Cannot deserialize value of type `java. util.LinkedHashMap<java.lang.String,java.lang.Double>

java - pig 单元 : Unable to open iterator

java - 如何为测试禁用 AWS 参数存储自动配置?

java - SpringTest 中的 ContextConfiguration 未加载

java - 类型参数 'S' 的推断类型 'S' 不在其范围内;应该扩展 'ua.com.store.entity.Country

java - 如何对依赖于springBoot applicationContext的方法进行单元测试?

java - 应用程序崩溃(android.view.InflateException)

Java JButton 不会遍历容器中的 JLabel(带有图像)

java - ParseQueryAdapter 加载图像不正确