Running multiple Tests fails (running one by one succeeds)

I’m following Chapter 11 - Testing on a company project, so it’s not the TIL App, but the structure for this particular part is basically the same. When testing my Users API, I always get a success on the first call and errors on the following ones. Testing every call separately succeeds, so my guess is that there is an error in reseting the database between tests. But this is what I don’t get, because the code of Application+Testable.swift is (apart from some minor naming changes and the addition of @discardableResult to sendRequest) the same to the one from the book - I even replaced the file of the chapter 11 “final” folder of the book and it runs perfectly there.

After 2 hours of debugging I give up finding the cause here, but I would be very happy if someone could have a look: https://github.com/bennokress/EventsAPI

The database configuration is the same as in the book, so to set docker up, this has to be executed: docker run --name postgres-test -e POSTGRES_DB=vapor-test -e POSTGRES_USER=vapor -e POSTGRES_PASSWORD=password -p 5433:5432 -d postgres

@0xtim Can you please help with this when you get a chance? Thank you - much appreciated! :]

@bennokress

It looks like the problem is caused by the standardUser variable that you are using to add a user to the database. When the first test runs, the database is reset. The test then successfully adds standardUser, but the create operation sets the id property of standardUser to the value determined by the database (in this case, 1). When the next test runs, the database is again reset, but standardUser already has an id assigned, so the create operation fails.

If you add the following line of code to your setup() method, it should fix the problem.

standardUser.id = nil

Another way would be to use code similar to the tests in TILApp, where the user was initialized at run time from individual variables (first name, last name, etc) and then added.

Hope that helps. Have fun!

1 Like

Thanks again for helping me out here. With your hint I could solve it even better by using this definition of standard which has the same effect:
static var standard: User { return User(firstName: "Benno", lastName: "Kress", username: "bkress", image: nil) }

1 Like