简体   繁体   中英

Moq How to use SetupAllProperties on a get only interface

I wanted to see if there is a way to get this

public interface IFoo
{
    int MyProp { get; }
}

[Fact]
public void Test
{
    var mock = new Mock<IFoo>();
    mock.SetupAllProperties();
    mock.Object.MyProp = 12; // this does not work because there is a get.
}

I know i can use mock.SetupGet but since there are lots of properties on my interface, I do not want to do SetupGet on each one of them.

You did not respond to my comment, but if you want to use reflection, you can find all properties (of the relevant type) and create Setup for each with this (the directive using System.Linq.Expressions; is needed for Expression class to be in scope; we create our own expression trees):

var mock = new Mock<IFoo>();

var parameterExpression = Expression.Parameter(typeof(IFoo));
foreach (var property in typeof(IFoo)
  .GetProperties().Where(x => x.PropertyType == typeof(int))
  )
{
  var lambdaExpression = Expression.Lambda<Func<IFoo, int>>(
    Expression.Property(parameterExpression, property),
    parameterExpression);
  mock.Setup(lambdaExpression).Returns(12);
}

Later addition: Not sure I really understand your question.

If you have many properties with many values, strongly typed, you can either do:

var mock = new Mock<IFoo>(MockBehavior.Strict);
mock.Setup(x => x.MyProp).Returns(12);
mock.Setup(x => x.MyOtherProp).Returns(3.14);
mock.Setup(x => x.MyThirdProp).Returns("test");
...
mock.Setup(x => x.MyLastProp).Returns(new DateTime(2015, 1, 1));
var objToUse = mock.Object;

or do:

var rep = new MockRepository(MockBehavior.Strict);
var objToUse = rep.OneOf((IFoo x) =>
    x.MyProp == 12
    && x.MyOtherProp == 3.14
    && x.MyThirdProp == "test"
    && ...
    && x.MyLastProp == new DateTime(2015, 1, 1)
    );

I do not think it can be made less cumbersome. If you want a loose mock, there is var objToUse = Mock.Of((IFoo x) => x.MyProp == 12 && ...); , almost a one-liner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM