gpt4 book ai didi

c# - NSubstitute 虚拟 getter 使用 ForPartsOf 返回替换抛出异常

转载 作者:太空狗 更新时间:2023-10-29 22:37:32 24 4
gpt4 key购买 nike

我正在尝试模拟一个对象的一个​​属性

有一个类似的问题: Returning the result of a method that returns another substitute throws an exception in 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>();
}

这些都失败了,但有一个异常(exception):

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

最佳答案

好的,这有点棘手。首先,解决方案是停止obj.PropClass从调用基本实现:

obj.When(x => { var get = x.PropClass; }).DoNotCallBase();
obj.PropClass.Returns(prop);

现在解释。 NSubstitute 记录了对替代者的调用,以及我们何时调用 Returns ,它会获取最后一次调用并尝试将其配置为返回特定值。

obj.PropClass.Returns(prop) 时发生了什么runs才是真正的obj.PropClass被称为,它又调用obj.PropClasses , 所以 NSubstitute 现在认为 obj.PropClasses是最后一次通话。 Returns然后尝试返回单个 PropClass什么时候PropClasses期望一个 IEnumerable<PropClass> ,因此异常(exception)。

上面的修复停止了 obj.PropClass立即调用基本实现,因此最后一次调用不会被 PropClasses 替换一个和Returns可以按预期工作。

不可否认,这非常糟糕,这也是我们坚持将部分模拟放入 NSubstitute 这么久的原因之一。 NSub 的漂亮语法是以它不能总是能够区分开发人员何时配置调用和何时需要运行实际代码为代价的。抱歉造成混淆。

关于c# - NSubstitute 虚拟 getter 使用 ForPartsOf 返回替换抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21294379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com