我正在尝试模拟对象的一个属性
有一个类似的问题: 返回返回另一个替代的方法的结果会在 NSubstitute 中引发异常 但是接受的答案对我不起作用。
void Main()
{
var obj = Substitute.ForPartsOf<MyObject>();
//WORKS, But I need a partial mock!:
//var obj = Substitute.For<MyObject>();
obj.PropClass.Returns(Substitute.For<PropClass>());
//It's suggestion, Fails, same error:
//var returnValue = Substitute.For<PropClass>();
//obj.PropClass.Returns(returnValue);
//Fails, same error:
//Lazy implementation of *similar question*
//Func<PropClass> hello = () => Substitute.For<PropClass>();
//obj.PropClass.Returns(x => hello());
//Fails, same error:
//I believe what *similar question* suggests
//obj.PropClass.Returns(x => BuildSub());
obj.PropClass.Dump("Value");
}
public class MyObject
{
public MyObject()
{
_propClasses = new List<PropClass>();
}
private readonly IList<PropClass> _propClasses;
public virtual IEnumerable<PropClass> PropClasses { get { return _propClasses; } }
public virtual PropClass PropClass { get { return PropClasses.FirstOrDefault(); } }
}
public class PropClass
{
}
public PropClass BuildSub()
{
return Substitute.For<PropClass>();
}
这些失败,但有以下例外:
CouldNotSetReturnDueToTypeMismatchException:
Can not return value of type PropClassProxy_9 for MyObject.get_PropClasses (expected type IEnumerable`1).
Make sure you called Returns() after calling your substitute (for example: mySub.SomeMethod().Returns(value)),
and that you are not configuring other substitutes within Returns() (for example, avoid this: mySub.SomeMethod().Returns(ConfigOtherSub())).
If you substituted for a class rather than an interface, check that the call to your substitute was on a virtual/abstract member.
Return values cannot be configured for non-virtual/non-abstract members.
Correct use:
mySub.SomeMethod().Returns(returnValue);
Potentially problematic use:
mySub.SomeMethod().Returns(ConfigOtherSub());
Instead try:
var returnValue = ConfigOtherSub();
mySub.SomeMethod().Returns(returnValue);