How to set the context path in Spring Boot WebMvcTest
<p>I'm trying to test my Rest controllers from my Spring Boot application and want the controllers to be available under the same path as in production.</p>

<p>For example I have the following Controller:</p>

<pre class="lang-java prettyprint-override"><code>@RestController
@Transactional
public class MyController {

    private final MyRepository repository;

    @Autowired
    public MyController(MyRepository repository) {
        this.repository = repository;
    }

    @RequestMapping(value = "/myentity/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity&lt;Resource&lt;MyEntity&gt;&gt; getMyEntity(
            @PathVariable(value = "id") Long id) {
        MyEntity entity = repository.findOne(id);

        if (entity == null) {
            return new ResponseEntity&lt;&gt;(HttpStatus.NOT_FOUND);
        }

        return new ResponseEntity&lt;&gt;(entity, HttpStatus.OK);
    }
}
</code></pre>

<p>Within my <code>application.yml</code> I have configured the context path for the application:</p>

<pre><code>server:
  contextPath: /testctx
</code></pre>

<p>My test for this controller looks as follows:</p>

<pre class="lang-java prettyprint-override"><code>@RunWith(SpringRunner.class)
@WebMvcTest(controllers = MyController.class, secure=false)
public class MyControllerTest {

    @Autowired
    private MyRepository repositoryMock;

    @Autowired
    private MockMvc mvc;

    @Test
    public void testGet() throws Exception {
        MyEntity entity = new MyEntity();
        entity.setId(10L);
        when(repositoryMock.findOne(10L)).thenReturn(entity);

        MockHttpServletResponse response = this.mvc.perform(
            MockMvcRequestBuilders.get("/testctx/myentity/10"))
            .andReturn().getResponse();
        assertEquals(response.getStatus(), 200);
    }

    @TestConfiguration
    public static class TestConfig {
        @Bean
        MyRepository mockRepo() {
            return mock(MyRepository.class);
        }
    }
}
</code></pre>

<p>This test fails since the status code is 404 for the call. If I call <code>/myentity/10</code> it works. Unfortunately the rest call is initiated by a CDC-Test-Framework (pact) so I cannot change the requested path (containing the context path <code>/testctx</code>). So is there a way to tell spring boot test to start the rest endpoint with a defined context path also during testing?</p>