简体   繁体   English

依赖于被调用接口的其他成员的单元测试方法

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

Let's say I have an interface called IOrderContainer :假设我有一个名为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该实现保留了一个私有的订单集合,该集合由公共只读集合Orders公开

AddOrder and RemoveOrder modifies the private collection. AddOrderRemoveOrder修改私有集合。

How would I unit test GetOrderById and RemoveOrder methods, if there's no public members on the interface to initialize the private orders collection?我将如何单元测试GetOrderByIdRemoveOrder方法,如果有在接口上没有公共成员初始化私人收藏的订单?

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 .最显而易见的方法是调用AddOrder一堆时间来填充私人收藏,但我觉得它违反了单元测试的定义,因为测试RemoveOrder / GetOrderById ,我们依赖于另一个“单位” - 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.另一种方法是不填充集合并检查例如 AddOrder 的行为是否正确:订单是否添加到集合的先前内容中。 But even then you are still testing two 'units' (the 'Addorder' method and the getter for the collection).但即便如此,您仍在测试两个“单元”(“Addorder”方法和集合的 getter)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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