Is there any way to load the configuration in Spring Boot application for one time?

Viewed 85

I'm looking for some recommendations or best practices to implement the unit test of spring boot application.

I have multiple classes of unit test and in each of those classes, I need to add the configuration like :

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootApplication.class)
public class ServiceRequestControllerTest{
...
}

So, when I run the goal maven test (mvn clean test), the spring configuration is loaded for multiple times. For example, I have five unit test classes, so, it loads the configuration five times which is slowing down the building of the project.

The question: is there any way to load this configuration just for one time for all the unit test classes?

2 Answers

use @ContextConfiguration annotation. the default behaviour for it is to reuse the context between tests.

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = SpringBootApplication.class)
public class ServiceRequestControllerTest{
...
}

We must always handle exceptions since it allows us to have greater contingency control. It is also necessary to always use JSON as a basis for Rest responses so we would have something like this:

@RestController
public class ControllerAddress {

    @PostMapping("/address")
    public ResponseEntity<?> postAddress(@RequestBody String address) {
        Map<String, Object> response = new HashMap<>();
        try {
            response.put("state", true);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            response.put("message", e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

But if you don't want to use JSON and you want a boolean variable true / false to respond directly, you can change the lines:

response.put("state", true);
return new ResponseEntity<>(response, HttpStatus.OK);

for:

return new ResponseEntity<>(true, HttpStatus.OK);
Related