title: UriComponentsBuilder/MvcComponentsBuilder usage in a Spring Boot Test
body: <p>I've put a very simple <a href="https://github.com/maxwellt/spring-boot-test-uricomponentsbuilder" rel="nofollow noreferrer">sample project on GitHub</a> to reproduce the problem.</p>
  
  <p>The main issue is that I have a <code>PersonController</code> that has a <code>PutMapping</code> to create a new person. In order to populate the <code>Location</code> header with the URL to fetch that person, I add the <code>UriComponentsBuilder</code> as parameter for that <code>PutMapping</code>, as you can see here:</p>
  
  <pre><code>  @PostMapping
    public ResponseEntity&lt;Person&gt; add(@RequestBody final PersonForCreate personForCreate, UriComponentsBuilder uriComponentsBuilder) {
      Person newPerson = new Person(this.people.size() + 1, personForCreate.getFirstName(), personForCreate.getLastName());
      this.people.add(newPerson);
  
      // create the URI for the "Location" header
      MvcUriComponentsBuilder.MethodArgumentBuilder methodArgumentBuilder = MvcUriComponentsBuilder.fromMappingName(uriComponentsBuilder, "getById");
      methodArgumentBuilder.arg(0, newPerson.getId());
      URI uri = URI.create(methodArgumentBuilder.build());
  
      return ResponseEntity.created(uri).body(newPerson);
    }
  </code></pre>
  
  <p>This works fine when running the project. But when running a test this results in an <code>IllegalArgumentException No WebApplicationContext</code>. The error comes from the <code>MvcUriComponentsBuilder.fromMappingName</code> call, but I have no idea why.</p>
  
  <p>My test looks as follows:</p>
  
  <pre><code>@ExtendWith(SpringExtension.class)
  @WebMvcTest
  class PersonControllerTest {
  
    @Autowired
    private PersonController personController;
  
    @Test
    void add() {
      this.personController.add(new PersonForCreate("Charles", "Darwin"), UriComponentsBuilder.newInstance());
    }
  }
  </code></pre>
  
  <p>I'm not sure if passing <code>UriComponentsBuilder.newInstance()</code> is correct, but I've tried with other values and notice no difference.</p>
  
  <p>FYI, The sample project uses Spring Boot 2.2.3 and JUnit 5, but I have the same problem using a sample project on JUnit 4.</p>