Marcos
Marcos

Reputation: 353

Testing Web Layer when Validation occurs in Service layer - Spring Boot Testing

I'm writing tests for my project which uses Spring Boot. It is a simple REST API with the typical Controller-Service-Repository structure.

I've been reading a lot lately about how to write my UNIT TESTS properly.

One of the articles I've read is this one:
https://medium.com/blog-quiqua/https-medium-com-blog-quiqua-unit-testing-your-api-controllers-879dbf01796f

The author states some problems I am facing right now in my project.

In my project, inside the "Web Layer", we make some security checks (mainly validate the Bearer token) and then just pass the incoming DTO to the "Service Layer" which is then responsible for validating it and throwing an Exception if the validation fails.

My question is simple: How would I write UNIT TESTS for my "Web Layer" expecting, say a BAD REQUEST, when the ValidationException -annotated with a @ResponseStatus(BAD_REQUEST)- is thrown from the "Service Layer"?

Am I just overthinking this too much and these tests should simply be Integration Tests instead of Unit Tests?

Thanks.

Edit:

The simple answer is to use Mockito when calling the Service method and throw a ValidationException and then check the response status code.

But there's another problem. If I have an entity called EntityDTO that has a name property with an arbitrary max length validation.

When the length is exceeded the Service throws a ValidationException with a custom message (i.e. "Name property max. length is X").

If my ValidationException is generic (thrown when any validation fails) I'm not testing "as it should be", right? At least that's my feeling...

Edit 2:

Marking the question as answered. The controller test should not test much logic, so it's fine if I only test for:

if request is OK

if request not valid in any type of way then is BAD REQUEST

If not found then is NOT FOUND

Etc...

Answering my last question if I need to test the Error Message when validation fails, then that's an integration test for the Web-Service Layers.

Upvotes: 1

Views: 426

Answers (1)

EricSchaefer
EricSchaefer

Reputation: 26370

Have the service injected as a Bean (e.g mark it as a Component) and mock it in your test. Then have the mock emit a ValidationException and assert on the Controller to return status code 400. I can not tell you how to do that exactly without knowing what your controller looks like, as there are several ways how to deal with responses.

Upvotes: 1

Related Questions