简体   繁体   中英

N-tier architecture and unit tests (using Java)

I'd like to have your expert explanations about an architectural question. Imagine a Spring MVC webapp, with validation API (JSR 303). So for a request, I have a controller that handles the request, then passes it to the service layer, which passes to the DAO one.

Here's my question. At which layer should the validation occur, and how ?

My though is that the controller has to handle basic validation (are mandatory fields empty ? Is the field length ok ? etc.). Then the service layer can do some tricker stuff, that involve other objets. The DAO does no validation at all. BUT, if I want to implement some unit testing (ie test layers below service, not the controllers), I'll end up with unexpected behavior because some validations should have been done in the Controller layer. As we don't use it for unit testing, there is a problem.

What is the best way to deal with this ? I know there is no universal answer, but your personal experience is very welcomed.

Thanks a lot. Regards.

In your service unit tests, craft your test data as though it passed all controller level validation checks - essentially assume that the controller level validation will work perfectly and your service will only ever receive data that is valid from the controller's perspective. Then, test each of those validation cases in the controller's unit tests. Finally, include integration tests which fail validation on both levels and make sure none get through.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM