简体   繁体   中英

Unit testing methods which depend on other member of the interface being called

Let's say I have an interface called IOrderContainer :

public interface IOrderContainer
{
    ReadOnlyCollection<Order> Orders { get; }
    void AddOrder(Order order);
    void RemoveOrder(Order order);
    Order GetOrderById(int orderId);
}

The implementation keeps a private collection of orders, which is exposed by a public read-only collection Orders

AddOrder and RemoveOrder modifies the private collection.

How would I unit test GetOrderById and RemoveOrder methods, if there's no public members on the interface to initialize the private orders collection?

The obvious way is to call AddOrder a bunch of times to populate the private collection, but I feel that it violates the definition of a unit test, because to test RemoveOrder / GetOrderById , we depend on another "unit" - AddOrder .

Should I create two constructors? One parameterless constructor and another one that takes in the collection and assigns it to the private collection.

A unit test checks an implementation (or better: its behaviour), not an interface. So it's perfectly OK to have an implementing class with multiple constructors, one having a parameter used to initialise the collection.

An alternative would be not to populate the collection and check if eg AddOrder behaves correctly: whether the order is added to whatever the previous content of the collection was. But even then you are still testing two 'units' (the 'Addorder' method and the getter for the collection).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM