开发者

Unit testing interfaces and method calls

开发者 https://www.devze.com 2023-01-04 20:45 出处:网络
There are two testing scenarios I am unclear on. Both appear at first sight to create very brittle tests.

There are two testing scenarios I am unclear on. Both appear at first sight to create very brittle tests.

First, when should one unit test the interface (i.e. ver开发者_如何学Cify that an interface has a set signature)?

Second, when should one "test the sequence diagram" (a term I just made up) - meaning verifying calls are being made to the appropriate objects?


Testing the interface means that you should only test the members which are available on the public interface. In other words, don't test private stuff. Take the unit under test as a black-box. This makes the tests more maintainable because you can change the implementation details without breaking the tests. Tests will also express what your unit under test is good for, not how it is implemented.

Testing calls made on other objects is called "interaction test" (not to be confused with integration tests, where you don't mock the other objects). Interaction tests are needed when your unit under test calls a method on another object without depending on it. I try to explain it with an example.

Following method needs to be tested:

public decimal CalculateTax(Order order);

Lets assume that this method needs to call

TaxRules TaxRuleProvider.GetRules(Country country)

which returns some local rules. When it doesn't call it, it will not be able to return the correct result. It will miss vital information. You don't need to test if it had been called, just test the result.

Another method:

public void StoreThingy(Thingy toBeStored);

It will call

public void NotificationBroker.NotifyChanges(SomeChanges x);

StoreThingy doesn't depend on the notification. You can't decide on its interface if it sent notifications or not. You need to test this by an interaction test.

Typically the methods for interaction tests return void. In this category are all kinds of events and notifications and methods like Commit().

0

精彩评论

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

关注公众号