Anders
Anders

Reputation: 53

Unit testing Spring Boot application endpoints

I have a small Spring Boot application with a defined health endpoint at "/health". This is defined in code by:

@Component
public class MyHealthEndpoint implements HealthIndicator {
  public Health health() {
    # ...
    # returns health info as JSON here 
    # ...
  }
}

So when running the application a visit to the endpoint at localhost/health returns some application health info.

My question is: what is the best way to test this?

I would like to do a unit test of the MyHealthEndpoint class and I've tried instantiating it in my test class with @Autowired which doesn't work. Also tried instantiating it in the test class with

MyHealthEndpoint testHealthEndpoint = new MyHealthEndpoint();

But this just returns an empty new class with no health info, so obviously the dependency injection/IOC in Spring Boot doesn't register it, or I'm just too much of a newbie to Spring to know how to do it correctly.

Is the only solution to run an integration test by starting the application and running a test http GET call directly to the endpoint and then asserting the returned JSON or do you have better ideas?

Upvotes: 3

Views: 5560

Answers (1)

Pusker György
Pusker György

Reputation: 408

You should use Sprint test context framework Check this: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#integration-testing-annotations

You can find the lib here: https://mvnrepository.com/artifact/org.springframework/spring-test

You should annotate the test classes (or a parent class) with @ContextConfiguration and you can set your config xml (locations parameter) and config Java classes (classes parameter) And if you use SpringMVC add @WebAppConfiguration annotation too

If it is configured you can use @Autowired in tests.

Upvotes: 1

Related Questions