Home > Back-end >  Integration testing a CRUD application - how can I create maintainable tests
Integration testing a CRUD application - how can I create maintainable tests

Time:07-13

I have small CRUD application that I would like to create integration tests for. I've seen the recommendation that "tests depending on other tests" is a no go. But how can I keep the code maintainable while at the same time not using the data from other tests?

So what I mean is easier to show by example with some pseudo code

TestCreateUser {
  make POST to API creating a user
  verify the a 200 is received back
}
TestReadUser {
  GET the user from the previous test.
  verify its the same user
}
TestUpdateUser {
  PATCH the user from the previous test.
  verify the user have the new data.
}

So this would be bad since all tests depend on the first one. So what are the alternatives? I guess I could use a beforeEach

@BeforeEach
public void initEach(){
  make POST to API creating a user
  verify the a 200 is received back
}

And then just skip the create user test. But this might create unnecessary calls if i for example have a test like this

TestCreateUserWithSpecialData {
  make POST to API creating a user with additional data
  verify the a 200 is received back
  verify the additional data is correctl
}

Then the beforEach would just create a user that the test does not need. Whats a good solution to solving this? Should I split them up into smaller classes and more files? Or are there a better solution? I suppose i could create if statements in the beforEach but that feels like a hack.

CodePudding user response:

You could use @BeforeAll to create some test data (once) and then have individual tests operate on it.

Or, for a test that’s doing something destructive like “delete”, you could create the user within the test itself.

(Purists might complain that this means the “delete” test will fail if the problem is actually with the “create” operation, but I don’t consider that a big problem — if something is sufficiently messed up with my testing environment that it can’t even create some test data, the exact number of tests that fail is not very interesting to me)

CodePudding user response:

You should use Mockito and a H2 database https://site.mockito.org/.

  • Related