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:

    return userService.find(username);


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?

1 Answer 1


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.

  • Thanks. do you think that for a function in the service layer that inserts data into the database or selects data from it such as a CRUD function the database should be mocked? I usually find myself keeping a group of "test" records in the database inserting them before any "unit" test.
    – arisalexis
    Sep 22, 2015 at 17:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.