我正在使用简单的转换器将字符串转换为枚举。这是自定义转换器:
@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/