mo_maat
mo_maat

Reputation: 2240

Mocking method that returns properties

How would I go about mocking a property on a method that returns a list of properties.

public class Data
{
  public string Property1 {get: set;}
  public string Property2 {get: set;}
  public string Property3 {get: set;}
}

public Data GetData(bool paramVal){
  Data myData = new Data();

  myData.Property1 = "Value1",
  myData.Property2 = "Value2",
  myData.Property3 = "Value3"

  return myData
}

How do I setup my mock on this method so that I can set the values in the properties?

What I tried:

MyDataBo = new Mock<IDataBo>`(); //(this is injected into my test class as a dependency)

MyDataBo.Setup(x => x.GetData(It.IsAny<bool>()).Property1).Returns("Value");`

It compiles but I get an error when debugging my test:

System.NotSupportedException: Unsupported express...

How can I mock Property1 or all the properties?

Upvotes: 1

Views: 542

Answers (2)

one way to solve this, SetupProperty, is to mock only the property.

var MyDataBo = new Mock<IDataBo>();

MyDataBo.SetupProperty(x => x.Property1, "value" );

Upvotes: 0

Nkosi
Nkosi

Reputation: 247531

An actual instance of the Data class is needed in this case.

Data myFakeData = new Data() {
    Property1 = "Value1",
    Property2 = "Value2",
    Property3 = "Value3"
};

var MyDataBo = new Mock<IDataBo>();

MyDataBo
    .Setup(_ => _.GetData(It.IsAny<bool>()))
    .Returns(myFakeData);

And the mock setup to return the fake data when the mocked member is invoked.

Upvotes: 1

Related Questions