【问题标题】:Object Not Updated in Unit Test单元测试中未更新对象
【发布时间】:2018-02-18 19:54:18
【问题描述】:

我正在尝试使用 Moq 和 xUnit 创建单元测试。该操作非常简单:计算日期范围内的天数并更新对象属性。这适用于集成测试,但是对象属性在我的单元测试中没有更新

单元测试:

[Fact]
public void Bill_DayCount_IsCorrect()
{
    // Arrange
    Mock<IRepository> mockRepo = new Mock<IRepository>();

    Bill bill = new Bill
    {
        StartDate = DateTime.Parse("2/1/2018"),
        EndDate = DateTime.Parse("3/1/2018"),
    };

    // Act
    mockRepo.Object.GetBillDayCount(bill);

    // Assert
    // Here the bill.DayCount value = 0
    Assert.Equal(28, bill.DayCount);
}

repo 中的方法:

public Bill GetBillDayCount(Bill bill)
{
    bill.DayCount = (bill.EndDate - bill.StartDate).Days;
    return bill;
}

【问题讨论】:

  • 你的测试用例没有任何意义。模拟是一种对依赖于外部组件的组件进行单元测试的有用技术,并且您希望控制该外部组件的行为方式。在您的示例中,您创建了 IRepository 接口的模拟,这意味着您的测试组件大多数是不同的类。 mockRepo.Object.GetBillDayCount(bill) 调用没有任何意义,因为 GetBillDayCount 方法背后没有实现。
  • @botond.botos 在本例中,Bill 对象依赖于来自Repository 类的方法,因此该测试旨在判断组件之间的交互。但是,在您发表评论之后,它已经被重构为让 GetBillDayCount 成为 Bill 类中的一个方法,这是一个更自然的地方。谢谢
  • 否决票没有问题,但请留下一些反馈,以帮助我更好地理解这个问题以及为什么它值得一票否决

标签: c# unit-testing asp.net-core xunit


【解决方案1】:

您不需要模拟作为测试目标的类。你可以使用Repository的具体实现。

您只需要模拟目标类使用的外部依赖项。

界面

public interface IRepository
{
    Bill GetBillDayCount(Bill bill);
}

public class Repository : IRepository
{
    public Bill GetBillDayCount(Bill bill)
    {
        bill.DayCount = (bill.EndDate - bill.StartDate).Days;
        return bill;
    }
}

测试

[Fact]
public void Bill_DayCount_IsCorrect()
{
    // Arrange
    var repository = new Repository();

    var bill = new Bill
    {
        StartDate = DateTime.Parse("1/1/2018"),
        EndDate = DateTime.Parse("29/1/2018"),
    };

    // Act
    var result = repository.GetBillDayCount(bill);

   // Assert
   Assert.Equal(28, result.DayCount);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多