Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mocking an interface derived from IList to pass it to Should().BeEquivalentTo()

I am currently testing a method that returns an instance of the IBuilding interface defined like this:

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; } 
}

Testing for the Name value is quite easy, but I’m struggling with the best way to test for the Zones to contain a given set of values.
Ideally, I would write this:

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

But this obviously does not compile.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The assembly where IBuilding is defined has public classes that implement IBuildingZone and IBuildingZones so I can use them like this:

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

but I’m not too happy to use classes from the assembly under test to be able to test it, especially when all that is needed are interfaces.

This is why I went looking for a way to mock expectedZones using the Moq framework but I’m a bit stuck trying to find a lean syntax for this.

Any suggestion is most welcome.

>Solution :

You can use anonymous objects to avoid using the types under test.

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);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading