我有一个测试,NSubstitute在假类中检查错误的调用。当我像下面的代码一样进行测试时,Received(...)
方法会检查值factory.featureClassName
是否会返回一次。
[Test]
public void CreateDataController_WhenCalled_CreatesServiceSettings()
{
var factory = Substitute.ForPartsOf<AbstractDataServiceFactoryFake>("fileName");
factory.CreateDataController();
factory.Received(1).CreateServiceSettings("fileName", factory.FeatureClassName);
}
一旦我必须使用以下代码,测试(像预期的那样)调用方法CreateServiceSettings(...)
:
[Test]
public void CreateDataController_WhenCalled_CreatesServiceSettings()
{
var factory = Substitute.ForPartsOf<AbstractDataServiceFactoryFake>("fileName");
var featureClassName = factory.FeatureClassName;
factory.CreateDataController();
factory.Received(1).CreateServiceSettings("fileName", featureClassName);
}
似乎Recieved()
方法与调用后给出的方法没有直接关联。任何人都可以解释一下,为什么会发生这种情况?
答案 0 :(得分:0)
这是NSubstitute语法的限制。
让我们分解第二个代码示例所发生的情况:
ee_pose = update_pose(ee_pose, px=-0.5, py=-0.5)
print(ee_pose)
# {'position': Point(x=-0.366, y=0.7096, z=0.3766), 'orientation': Quaternion(x=0.7468, y=-0.5236, z=-0.2663, w=-0.3115)}
在第一个代码示例中,我们得到了这个:
0
换句话说,NSubstitute看到第二个代码示例如下:
factory
.Received(1) // ... check the next call has previously been received
.CreateServiceSettings("fileName", className)
// call is made to CreateServiceSettings, NSub checks
// it was received.
为了避免这种情况,避免在断言(如factory
.Received(1) // ... check the next call has previously been received
.CreateServiceSettings("fileName", factory.FeatureClassName)
// before CreateServiceSettings is invoked, its arguments
// must be evaluated. So factory.FeatureClassName
// is called next and NSubstitute checks that.
)或配置(如var _ = factory.Received(1).FeatureClassName;
factory.CreateServiceSettings("fileName", _);
)期间回调替换是很有用的。