在单元测试 getter/setter 时如何使用 Rhino-mocks?
我目前正在学习 Rhino-mocks,并认为我混淆了单元测试和模拟之间的界限。在下面的示例中,我有一个只读 Count() 属性,我试图在其上测试 Get() (一个非常人为的示例,仅用于讨论目的)。正如 Assert.AreEqual 上的注释所示,Count() 属性的结果是 2,而它应该是 3。
我的问题是我可以使用 Rhino-mocks 来实际存根一个对象(在本例中是一个只读属性)并测试模拟 IProduct 对象的 get_Count() 属性的逻辑?
public interface IProduct
{
int Count { get; }
}
public class Product : IProduct
{
private int count;
public int Count
{
get { return count + 1; }
}
}
public class TestFixture
{
[NUnit.Framework.Test]
public void TestProduct()
{
MockRepository mock = new MockRepository();
IProduct product = mock.Stub<IProduct>();
product.Stub(p => p.Count).Return(2);
mock.ReplayAll();
Assert.AreEqual(3, product.Count); //Fails - result from product.Count is 2
mock.VerifyAll();
}
}
I'm currently learning Rhino-mocks and think I'm confusing the line between unit testing and mocking. In my example below, I have a readonly Count() property for which I am trying to test the Get() on (a very contrived example for discussion purpose only). As the comment on the Assert.AreEqual indicates, the result from the Count() property is 2 when it should be 3.
My question is can I use Rhino-mocks to actually stub an object (in this case a readonly property) and test the logic of the get_Count() property of the mock IProduct object?
public interface IProduct
{
int Count { get; }
}
public class Product : IProduct
{
private int count;
public int Count
{
get { return count + 1; }
}
}
public class TestFixture
{
[NUnit.Framework.Test]
public void TestProduct()
{
MockRepository mock = new MockRepository();
IProduct product = mock.Stub<IProduct>();
product.Stub(p => p.Count).Return(2);
mock.ReplayAll();
Assert.AreEqual(3, product.Count); //Fails - result from product.Count is 2
mock.VerifyAll();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在模拟您要测试的对象。这从根本上来说是不正确的——您想要模拟(或存根)对您尝试测试的对象的依赖关系。
在上面所示的情况下,您根本不会使用模拟。
另请参阅我对 AAA 语法的评论。
You are mocking out the object you are trying to test. This is fundamentally incorrect--you want to mock (or stub) DEPENDENCIES on the objects you are trying to test.
In the case shown above, you would not use mocking at all.
Also see my comment on AAA syntax.