开发者

When I test a method, do I trust that other methods work?

If I'm unit testing method A and I use a number of other methods (or property getters) in my test to check its behavior (I'm not using mocks in this case), is it good practice to trust that those other methods work p开发者_如何学编程roperly and assume that if they don't it will be caught in tests on those methods?


In short, yes.

The very nature of unit testing is that you are verifying that some atomic "unit" of code produces the correct result in a series of known situations. The test should be performed as if in a vacuum; any code on which your unit depends should be spoofed (usually via a mock) to produce the expected inputs. Those dependencies should also have their own unit tests that will verify that they would produce those expected inputs to their dependents in the same situation.


Yes, you should test only a single method/unit. For instance TestNG encourages you to make such an assumptions by allowing you to define test dependencies. If you test method foo() which depends on method bar(), make your test dependent on the one that tests bar(). If bar() test(s) fail, tests for foo() won't even run.

The downside of this assumption (when you don't have the ability to define test dependencies) is that when bar() method is broken, tests for both foo() and bar() will fail, making it harder to find the root cause of the problem.


If you really distrust some other methods then you should write unit tests for those methods. Even if the bad method causes your unit test to fail, it will also fail its own unit test and this will lead the programmer to fix the right bug.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜