Home > OS >  How can I test this
How can I test this

Time:12-04

Lets say I have the following code, and I want to test that the Data class is correctly calling the Update() methods of the two item classes when Dowork() is called.

`

    public class Item1
    {
        public string Name { get; private set; }

        public void Update(string value) { Name = ...; }
    }

    public class Item2
    {
        public string Name { get; private set; }

        public void Update(string value) { Name = ...; }
    }


    public class Data
    {
        public Item1 Item1 { get; set; }
        public Item2 Item2 { get; set; }

        public void Dowork()
        {
            Item1.Update("Q");
            Item2.Update("W");
        }

    }

`

How can I achieve that if I can't modify the Item1 and Item2 classes (external code) to add interfaces that can be mocked?

One option is to check Item.Name and Item2.Name before and after Dowork() is called in a test, but aren't I then testing the implementations of Item1 and Item2? i.e if Item1 or Item2 change then my test breaks even though I am not testing their behaviour.

All I really care about is that Data is calling the Update methods when DoWork is called, not what the Item classes happen to do at that point.

CodePudding user response:

I would like to recommend you NSubstitute nuget package that you can use for mocking and check the method call easily.

[Fact]
public void Check_Method_Call()
{
  var item1= Substitute.For<Item1>();
  var item2= Substitute.For<Item2>();
  var data= new Data()
           {
             Item1=item1,
             Item2=item2
           };

  //call update methods
  data.Dowork();

  //check method calls
  item1.Received(1).Update("Q");//or you can use Arg.Any<string>()
  item2.Received(1).Update(Arg.Any<string>());

}
  • Related