【问题标题】:Mocking an interface derived from IList to pass it to Should().BeEquivalentTo()模拟从 IList 派生的接口以将其传递给 Should().BeEquivalentTo()
【发布时间】:2022-04-19 22:34:05
【问题描述】:

我目前正在测试一个返回IBuilding 接口实例的方法,定义如下:

public interface IBuilding
{
    public string Name { get; set; }
    public IBuildingZones Zones { get; set; }
}

public interface IBuildingZones: IList<IBuildingZone> 
{ 
    public void SortByElevation();
}

public interface IBuildingZone
{
    public string Name { get; set; }
    public double Elevation { get; set; } 
}

测试Name 值非常容易,但我正在努力寻找测试Zones 以包含一组给定值的最佳方法。 理想情况下,我会这样写:

    building.Zones.Should().BeEquivalentTo(
        {
            { "garage", 0 },
            { "living_room", 10 },
            { "master bedroom", -4.2 }
        }
    ); 

但这显然不能编译。

定义IBuilding 的程序集具有实现IBuildingZoneIBuildingZones 的公共类,因此我可以像这样使用它们:

    var expectedZones = new BuildingZones
    {
        new BuildingZone("garage", 0),
        new BuildingZone("living_room", 10),
        new BuildingZone("master_bedroom", -4.2)
    };
    building.Zones.Should().BeEquivalentTo(expectedZones);

但是我不太乐意使用被测程序集中的类来测试它,尤其是当只需要接口时。

这就是为什么我去寻找一种使用 Moq 框架来模拟 expectedZones 的方法,但我在试图为此找到一个精简的语法时有点卡住了。

任何建议都是最受欢迎的。

【问题讨论】:

    标签: c# moq fluent-assertions


    【解决方案1】:

    您可以使用匿名对象来避免使用被测类型。

    var expected = new[]
    {
       new { Name = "garage", Elevation = 0.0 },
       new { Name = "living_room", Elevation = 10.0 },
       new { Name = "master bedroom", Elevation = -4.2 }
    };
    
    building.Zones.Should().BeEquivalentTo(expected);
    
    

    【讨论】:

    • 太棒了,我不知道这种语法。作为其他人的旁注,必须使用0.010.0 来强制所有值都使用double 类型,否则会出现CS0826 错误。
    猜你喜欢
    • 2019-01-21
    • 1970-01-01
    • 2014-11-13
    • 2013-04-15
    • 1970-01-01
    • 2012-07-25
    • 2019-05-01
    • 2017-10-11
    • 2020-06-09
    相关资源
    最近更新 更多