How to Test a REST Service Without Being Excessive

integration-teststddunit testing

So I have a REST backend (in node.js or Java doesn't matter but the example is in js).

I try to have a service for each endpoint so that the /users endpoint has two files:

usersRouter.js which includes the router endpoints with example code:

router.get('/users/:username',function(req,res,next){ 
    return userService.find(username);
}

userService.js

function find(username) { //do some database stuff here }

I think best practices call for testing all methods in your app with both unit testing the service and integration testing the endpoint.

Is it really necessary in this case? If the endpoint only calls one method then I could test only this one with all the available scenarios.

A downside would be that the function has more options that are not used by the endpoint and could be used by another endpoint/function but is it too much to test almost the same thing twice?

Best Answer

When unit-testing the service layer, those tests should only verify the logic in the service layer itself and they should be fast and isolated from possible failures that lie outside the service layer. This means that in the unit-tests of the service layer, dependencies of the service layer that can't be "guaranteed" to be error free or that might cause a slowdown of the tests. In particular, the database access should be mocked in the unit tests, because databases cause a lot of trouble in unit tests (in part due to slowness of the connection, and in part because they persist state between tests, which makes it hard to keep the tests independent).

In the integration tests of the endpoint, you would test all code that is involved when the end-point gets used, including the database.

If there is little logic in a particular function in the session layer, then you might forego unit-testing that function. This could be based on a risk assessment on how big the chance is that something will be wrong in that function that wouldn't be caught in another way.

Related Topic