无法在单元测试中使用自定义弹簧转换器

sky*_*ker 5 java spring spring-mvc spring-boot

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

@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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

@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"));
}
Run Code Online (Sandbox Code Playgroud)

}

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

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
Run Code Online (Sandbox Code Playgroud)

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

Sub*_*lil 7

如果有人使用implementsorg.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();
  }
Run Code Online (Sandbox Code Playgroud)

  • 我花了两个小时才使其工作,你的解决方案非常完美!太感谢了! (2认同)

cac*_*co3 5

conversionService是一个模拟。

所以这:

conversionService.addConverter(new SessionStateConverter());
Run Code Online (Sandbox Code Playgroud)

调用addConverter模拟。这对你没有任何用处。

我相信您想使用 real FormattingConversionService:要做到这一点,您需要@Mock从字段中删除注释conversionService并使用真实的实例FormattingConversionService

private FormattingConversionService conversionService = new FormattingConversionService();
Run Code Online (Sandbox Code Playgroud)

如果您需要像模拟检查一样跟踪真实对象的调用:@Spy