How do you write unit tests that involve databases?
In Node.js, I wrote a twitter 开发者_运维问答client. How can I write unit tests that involve people posting threads and stuff?
In a word, stubs. When unit testing, write stub functions for your Twitter API calls that simply return the same data and responses each time. You're not testing Twitter's API, after all.
When you write your tests first(TDD) it becomes more naturally to do something called dependency injection. Uncle Bob practices three rules when doing TDD:
Over the years I have come to describe Test Driven Development in terms of three simple rules. They are: You are not allowed to write any production code unless it is to make a failing unit test pass. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
You must begin by writing a unit test for the functionality that you intend to write. But by rule 2, you can't write very much of that unit test. As soon as the unit test code fails to compile, or fails an assertion, you must stop and write production code. But by rule 3 you can only write the production code that makes the test compile or pass, and no more.
If you think about this you will realize that you simply cannot write very much code at all without compiling and executing something. Indeed, this is really the point. In everything we do, whether writing tests, writing production code, or refactoring, we keep the system executing at all times. The time between running tests is on the order of seconds, or minutes. Even 10 minutes is too long.
You can also do stubbing with I think some popular stubbing-frameworks:
- https://github.com/felixge/node-gently
- https://github.com/cjohansen/Sinon.JS
https://github.com/joyent/node/wiki/modules#testing
精彩评论