I want to use moq a void method and set a value to a protected property when is called.
public class MyClass{ public Guid Id {get; protected set; } }
public interface IMyRespository { public开发者_高级运维 void Save(MyClass myClass); }
Something like:
var moq = new Mock<IMyRespository>();
var my = new MyClass();
moq.Setup(x=>x.Save(my));
I want to setup that Id on save is no more a Guid.Empty. Save is a void method so no returns, and using:
.Callback(() => my = new MyClassImpl(new Guid("..")))
is not working..
First, you have to set up the expectation properly. I think what you actually want is to set up the mock so that it accepts any instance of MyClass
:
moq.Setup(x=>x.Save(It.IsAny<MyClass>()));
Then, you set up a callback like so:
moq.Setup(x=>x.Save(It.IsAny<MyClass>()))
.Callback((myClassParam) => my = myClassParam);
Putting it all together will let you construct a mock that accepts MyClass
and saves the MyClass
instance to my
variable:
[TestMethod]
public void Test() {
var moq = new Mock<IMyRespository>();
MyClass my = null;
moq.Setup(x=>x.Save(It.IsAny<MyClass>()))
.Callback((myClassParam) => my = myClassParam);
var newMyClass = new MyClassImpl(new Guid(".."));
moq.Object.Save(newMyClass);
Assert.AreSame(newMyClass, my);
}
精彩评论