我正在测试REST API。假设它返回JSON结构。什么是测试服务器的最佳方法?如果所有先前的步骤都成功,则每个测试步骤都只能成功。
结构A:一次测试所有内容
- Test method 1:
- make server request
- assert http response code was 200
- assert returned file is not empty
- assert returned file has valid JSON syntax
- assert returned JSON contains key X
这似乎是最好的解决方案。
优点:
- 仅一个服务器请求
- 我正在整体测试行为“服务器是否使用键X返回JSON?”
结构B:向每个测试逐渐添加断言
- Test method 1:
- make server request
- assert http response code was 200
- Test method 2:
- make server request
- assert returned file is not empty
- Test method 3:
- make server request
- assert returned file has valid JSON syntax
- Test method 4:
- make server request
- assert returned JSON contains key X
这是我开始出来做,我相信,这应该是去,因为每一个方法只测试方式单一的事情,这创造了更好的分离。但是现在我认为,既然这些不是单元测试,那么我的分离是不合适的,我应该测试整个行为。
结构C:发出请求一次,并对缓存的响应运行单独的测试方法
- make server request and cache it (allow read-only access)
- Test method 1:
- assert http response code was 200 on cached server request
- Test method 2:
- assert returned file is not empty on cached server request
- Test method 3:
- assert returned file has valid JSON syntax on cached server request
- Test method 4:
- assert returned JSON contains key X on cached server request
优点:
- 没有重复的(昂贵的)服务器请求
- 仍有单断言测试方法
使用哪种最明智的测试结构?