I am using simple converter for converting string to enum. Here is the custom converter:
@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;
}
}
}
Currently I am using UserSessionState as PathVariable
in my rest controller. The implementation works as expected. However when I try to unit test the rest controller it seems that conversion does not work and it does not hit the controller method.
@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"));
}
}
In debug mode I get following error:
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
In my opinion the mock for conversion service does not work. Any ideas?
Method SummaryReturn true if objects of sourceType can be converted to the targetType . Return true if objects of sourceType can be converted to the targetType . Convert the given source to the specified targetType . Convert the given source to the specified targetType .
Spring provides out-of-the-box various converters for built-in types; this means converting to/from basic types like String, Integer, Boolean and a number of other types. Apart from this, Spring also provides a solid type conversion SPI for developing our custom converters.
java. Spring Boot provides an easy way to write a unit test for Rest controller. With the help of SpringJUnit4ClassRunner and MockMVC, a web application context can be created to write unit test for Rest controller. First, we add the necessary annotations to our test class as in the previous test.
The conversionService
is a mock.
So this:
conversionService.addConverter(new SessionStateConverter());
calls addConverter
on mock. This does nothing useful for you.
I believe you want to use real FormattingConversionService
: to do it you need to remove @Mock
annotation from conversionService
field and use a real instance of FormattingConversionService
instead:
private FormattingConversionService conversionService = new FormattingConversionService();
If you need to track invocations on real objects as you would do on mock check out : @Spy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With