haykart
haykart

Reputation: 957

Spring boot: should validation been tested when testing controller layer

I am working on the project where I want to have decent test-infrastructure. I am using spring boot, which makes easier for testing separate layers of the project: for example

If I want to test controller layer I will mock (with mockito) service dependencies of the controller, and check whether right service method will be called on given http request, and expected http status will be returned. If I want to test service layer I will mock repository and business logic dependencies. And so on.

In my project, I am using spring validators to check whether request body is passed correctly (with the use of @InitBinder method I am adding my custom validators to the WebDataBinder, and with use of @Valid annotation, those validators are called on the parsed request body).

So my question is: is it good practice to mock validators and test only controller logic (validators will be tested in context of validator layer)? I am just not sure which is the best practice, and is it normal to test validators along with controllers?

Upvotes: 1

Views: 959

Answers (1)

Yogi
Yogi

Reputation: 1895

Mocking is not always best option, when you are testing your controller logic, validation logic and especially business logic. I would not recommend to mock any of these.

You can use various framework to test:

  1. Controller logic - RestAssured or MockMvc
  2. Business logic - Plain JUnit tests under SpringBootTest and SpringRunner
  3. Validation logic - Plain JUnit tests under SpringBootTest and SpringRunner

For further reading:
RestAssured: http://rest-assured.io/
Spring validator test: Writing JUnit tests for Spring Validator implementation

Upvotes: 1

Related Questions