Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Integration Test Results in 401

Tags:

spring-boot

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.

like image 381
Bex Avatar asked Aug 23 '16 18:08

Bex


2 Answers

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
like image 174
Bex Avatar answered Oct 20 '22 08:10

Bex


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 )

like image 31
Adam Avatar answered Oct 20 '22 10:10

Adam