Spring [SOLVED]: Unable to resolve place holder in Mockito Unit test

Spring [SOLVED]: Unable to resolve place holder in Mockito Unit test

Home Forums Frameworks Spring Spring [SOLVED]: Unable to resolve place holder in Mockito Unit test

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #112915

    Cloudy Point
    Keymaster

    QuestionQuestion

    The Controller that I’m trying to write unit test case for is as follows –

    @RequestMapping("${rest.base.path}/plugin")
    public class Controller {
    .
    .
    .
    } 
    

    The Unit test case is setup –

    @RunWith(MockitoJUnitRunner.class)
    public class ControllerTest {
    
        @Autowired
        private MockMvc mvc;
    
        @InjectMocks
        Controller dataController;
    
        @Mock
        PluginService pluginService;
    
    
        @Test
        public void createFiles() throws Exception {
            this.mvc = MockMvcBuilders.standaloneSetup(dataController).build();
            mvc.perform(MockMvcRequestBuilders.get("/dc/plugin")
                    .contentType(MediaType.APPLICATION_JSON));
        }
    

    On running the unit test, it’s unable to resolve the placeholder ${rest.base.path} as I’m not loading the Spring Context. I tried setting the System.setProperty(“rest.base.path”, “/api”) without any success. Is there anyway I can assign value to that placeholder without removing @RunWith(MockitoJUnitRunner.class)?

    #112916

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    The key here is to fill placeholder yourself calling StandaloneMockMvcBuilder.addPlaceholderValue

    As the documentation states:

    In a standalone setup there is no support for placeholder values embedded in request mappings. This method allows manually provided placeholder values so they can be resolved.

    So, the following simple snippet should work for you

    public class TestController {
    
    private MockMvc mockMvc;
    
    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(new Controller()).addPlaceHolderValue("rest.base.path", "dc")
                .setControllerAdvice(new ExceptionMapper())
                .setMessageConverters(new MappingJackson2HttpMessageConverter(new ExtendedObjectMapper())).build();
    }
    
    @Test
    public void testGet() throws Exception {
        mockMvc.perform(get("/dc/plugin").accept(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk());
    }}
    

    For sure, you can achieve the same autowiring your controller.

    Source: https://stackoverflow.com/questions/43992597/unable-to-resolve-place-holder-in-mockito-unit-test
    Author: Sergey Prokofiev
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.