gpt4 book ai didi

c# - Rhino Mocks 的 AssertWasCalled 在测试方法中模拟的属性分配

转载 作者:行者123 更新时间:2023-11-30 14:35:03 30 4
gpt4 key购买 nike

使用 Rhino Mocks 3.6,给出下面的代码我希望 AssertWasCalled 断言通过,但它没有。取而代之的是失败的断言消息:

"Rhino.Mocks.Exceptions.ExpectationViolationException: IBar.set_Model(7); Expected #1, Actual #0."

尝试 IgnoreArguments() 不会更改结果,但将 IBar 属性更改为方法并断言使用参数调用该方法确实有效。

我在这里错过了什么?

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;

public interface IFoo { }
public interface IBar { int Model { get; set; } }
public class Bar : IBar { public int Model { get; set; } }

public class Foo : IFoo
{
public void MyMethod(IBar bar)
{
bar.Model = 7;
}
}

[TestClass]
public class TestFoo
{
[TestMethod]
public void MyMethod()
{
var foo = new Foo();

var mockBar = MockRepository.GenerateStub<IBar>();
foo.MyMethod(mockBar);

mockBar.AssertWasCalled(b => b.Model = 7);
}
}

最佳答案

如果你正在 stub 你的 bar 对象,那么你应该对属性的值进行断言

Assert.AreEqual(7, mockBar.Name);

如果你想测试期望,你应该生成模拟而不是 stub

var mockBar = MockRepository.GenerateMock<IBar>();
foo.MyMethod(mockBar);
mockBar.AssertWasCalled(b => b.Model = 7);

Difference between stubs and mocks :

A mock is an object that we can set expectations on, and which will verify that the expected actions have indeed occurred. A stub is an object that you use in order to pass to the code under test. You can setup expectations on it, so it would act in certain ways, but those expectations will never be verified. A stub's properties will automatically behave like normal properties, and you can't set expectations on them.

If you want to verify the behavior of the code under test, you will use a mock with the appropriate expectation, and verify that. If you want just to pass a value that may need to act in a certain way, but isn't the focus of this test, you will use a stub.

关于c# - Rhino Mocks 的 AssertWasCalled 在测试方法中模拟的属性分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12963744/

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