【问题标题】:How to test remove method without first adding elements如何在不先添加元素的情况下测试删除方法
【发布时间】:2022-01-21 16:02:54
【问题描述】:

我有一个有两个方法 add(obj) 和 remove(obj) 的类。当最初包含添加的属性的私有集合是私有的并且我已经读过访问私有字段以进行单元测试时,如何对 remove 方法进行单元测试。如果我首先使用 add 方法填充集合,则测试将不是单元测试,因为当 add 方法不起作用时它可能会失败。

class A
{
    private readonly ICollection<object> objs = new List<object>();

    public IReadOnlyCollection<object> Objs => this.objs.ToList();

    public void Add(object obj)
    {
        this.objs.Add(obj);
    }

    public void Remove(object obj)
    {
        this.objs.Remove(obj);
    }
}

【问题讨论】:

  • ....collection the test will not be a unit test because it can fail when the add method doesn't work. 我没有发现问题。这是一个常见的场景,即必须使用被测功能以外的功能来创建状态。如果您有 2 个失败的单元测试在 Add 上都失败,即使 Remove 正在其中一个测试中,IMO 也可以。
  • 你可以使用objs.Remove(obj)的返回值来判断它是否真的可以移除特定的对象。

标签: c# unit-testing


【解决方案1】:

它仍然是一个单元测试,因为您的单元是A

进行一些设置是完全可以的。

有时不止一项测试失败。在您的情况下,如果 Add 不起作用,则 Remove 测试失败。

// It is possible to add item to A.
// Arrange.
var sut = new A();
// Act.
sut.Add("a");
// Assert.
sut.Objs.Single().Should().Be("a", Reason: "Item is added.");
// It is possible to remove item from A.
// Arrange.
var sut = new A();
sut.Add("a");
sut.Objs.Single().Should().Be("a", Reason:"Sanity check");
// Act.
sut.Remove("a");
// Assert.
sut.Objs.IsEmpty(Reson: "Item is removed.");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 2014-07-23
    • 2019-10-23
    相关资源
    最近更新 更多