开发者

Moq modify protected on calling void method

开发者 https://www.devze.com 2023-01-12 10:40 出处:网络
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; } }

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

精彩评论

暂无评论...
验证码 换一张
取 消