6

We've got a Spring Boot 1.4 web app the exposes a REST api, and we want to run some integration tests.

In our test, we get Spring Boot to spin up the web app locally and then we make some calls against the api.

If we simply run the web app itself and hit the endpoint, we get 200/OK response, which is expected. Running the test, however, we are getting a 401/Unauthorized server response.

Where would I look to see what might be causing the authorization error?

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class DemoApplication3IT {
    private final Logger log = LoggerFactory.getLogger(DemoApplication3IT.class);

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void getFunky() throws IOException {
        ResponseEntity<String> response =
            this.restTemplate.getForEntity("http://localhost:8080/api/funky", String.class);
        log.info("TestRestTemplate response Code: " + response.getStatusCode());
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); // Expected :200, Actual   :401
    }
}

It's strange that hitting the endpoint with a browser works fine, but the integration test fails.

Bex
  • 573
  • 2
  • 6
  • 16
  • Can you include the configuration of your `Application.class` that defines the security? Something is protecting the endpoint and causing the 401 to be returned. – Shawn Clark Aug 24 '16 at 06:31
  • It's a large, proprietary application, so sharing is problematic. :( Are there typical beans we'd look for? I could probably sanitize them and share. – Bex Aug 24 '16 at 17:49

2 Answers2

4

Ultimately, the issue was that security had not been disabled in the unit test environment. The solution was adding the following lines to application.yml:

management.security.enabled: false
management.health.db.enabled: false
security.basic.enabled: false
Bex
  • 573
  • 2
  • 6
  • 16
1

You can also add it like this in your test class to save duplicating the application.properties:

 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
        classes = { TestDataSourceConfig.class },
        properties = {
                "security.basic.enabled=false"
        })

It should also be turned off by this annotation:

@AutoConfigureMockMvc(secure = false)

but currently I can't get that to work (maybe there'll be an answer in future: Spring Boot integration test ignoring secure=false in AutoConfigureMockMvc annotation, get 401 )

Adam
  • 5,215
  • 5
  • 51
  • 90