开发者

Testing REST API with database backend

开发者 https://www.devze.com 2023-04-03 19:29 出处:网络
I want to k开发者_高级运维now the best/different ways to test a REST API which uses a database backend. I\'ve developed my API with Flask in Python and want to use unittest or nose.

I want to k开发者_高级运维now the best/different ways to test a REST API which uses a database backend. I've developed my API with Flask in Python and want to use unittest or nose.

But my problem, is that some resources require another resource to create them in the first place. Is there a way to say that to test the creation of a blog post requires that another test involving the creation of the author was successful?


There are 2 standard ways of approaching a test that depends on something else (object, function call, etc).

  • You can use mocks in place of the objects the code you are testing depends on.
  • You can load a fixture or do the creation/call in the test setup.

Some people like "classical" unit tests where only the "unit" of code is tested. In these cases you typically use mocks and stubs to replace the dependencies.

Other like more integrative tests where most or all of the call stack is tested. In these cases you use a fixture, or possibly even do calls/creations in a setup function.

Generally you would not make one test depend on another. All tests should:

  • clean up after themselves
  • be runnable in isolation
  • be runnable as part of a suite
  • be consistent and repeatable

If you make one test dependent on another they cannot be run in isolation and you are also forcing an order to the tests run. Enforcing order in tests isn't good, in fact many people feel you should randomize the order in which your tests are run.


The unit test should work in isolated mode so you have to isolate your dependent resources and this done using isolation an framework (mocking framework). Common frameworks for legacy, Windows systems are DevMagicFake, MOQ, Rhino Mocks, TypeMock.

DevMagicFake will make you able to fake the DB so you will not need to create DB or even any code to save your data because it save your data in memory and you can retrieve it anytime.

0

精彩评论

暂无评论...
验证码 换一张
取 消