Hacker News new | ask | show | jobs
by tdbgamer 3158 days ago
I am generally for TDD, but I don't think APIs really need heavy code coverage.

That said, testing the input/output directly doesn't work well because now a single change the output data (adding a field to the JSON for example) will call tons of tests to fail.

I usually use or create some JSON serialization/deserialization classes and use those to generate fake data and ensure that the API returns 200 responses.

That way if I add a field to the JSON objects, my tests are unaffected and will generate the new fields in the tests.

So I may do something like this (Python-ish):

    new_user = User.generate_user()
    response = api.post('/users', new_user.serialize())
    assert response.status_code == 200
    
    response = api.get('/users')
    users_json = json.loads(response)
    users = {}
    for user in users_json:
        users.add(User.unserialize(user))
    assert new_user in users
That way changes to the User JSON will not impact tests and I still have some basic sanity checks.

Hope that helps.

1 comments

Nice, thanks :)

Do you have any good resources on testing? Books/articles etc.?

I often have the feeling the only people who write about this stuff are the die hard TDD gurus.

No problem!

I did read Clean Code by Robert Martin. He's definitely in the "die hard TDD guru" category, but there are still useful examples to be extracted from the book.

Besides that, I mainly learned a lot of testing tricks in the wild, reading through Github projects. My learning process now-a-days is mostly:

1. Discover a really cool trick or concept I didn't know existed in a Github project. 2. Research the hell out of it. 3. Try to use it in some personal example project.