我正在使用简单的转换器将字符串转换为枚举。这是自定义转换器:
@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;
}
}
}
目前我在休息控制器中使用 UserSessionState 作为
PathVariable
。实施按预期进行。然而,当我尝试对其余控制器进行单元测试时,似乎转换不起作用并且没有命中控制器方法。
@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"));
}
}
在调试模式下,我收到以下错误:
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
在我看来,转换服务的模拟不起作用。 有什么想法吗?
如果有人使用implements
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();
}
conversionService
是一个模拟。
所以这个:
conversionService.addConverter(new SessionStateConverter());
在模拟中调用
addConverter
。这对你没有任何用处。
我相信您想使用真实的
FormattingConversionService
:为此,您需要从 @Mock
字段中删除 conversionService
注释,并使用 FormattingConversionService
的真实实例来代替:
private FormattingConversionService conversionService = new FormattingConversionService();
@Spy
对于使用 SpringBootTest 和 AutoConfigureMockMvc 的任何人
@EnableWebMvc
@AutoConfigureMockMvc(addFilters = false)
@SpringBootTest(classes = {MyController.class, MyConverter.class})
class TestController {
@Autowired
private FormattingConversionService conversionService;
@Autowired
MyConverter myConverter;
@BeforeEach
void setUp() {
conversionService.addConverter(entityConverter);
}
}