是否可以使用 Rhino Mocks 生成部分存根?
一般来说,我对单元测试和模拟很陌生,我正在尝试为我的一个类设置测试,我想确保从同一类中的另一个方法调用特定方法。 因此,我想使用具体的实现,但模拟其中的一部分。 这可能吗?
public class MyClass { public Accounts[] GetAccounts() { return GetAccounts(null); } public Accounts[] GetAccounts(CustomerId id) { if(id == null) { // Get all accounts } } }
因此,我尝试设置一个存根来调用 GetAccounts() (我想使用具体实现),但我想检查该方法是否调用 GetAccounts(null)。
[Test] public void GetAccountsTest() { MockRepository mocks = new MockRepository(); MyClass stub = mocks.Stub(); using(mocks.Record()) { Expect.Call(() => stub.GetAccounts()).CallOriginalMethod(); Expect.Call(() => stub.GetAccounts(null)); } mocks.ReplayAll(); stub.GetAccounts(); mocks.VerifyAll(); }
问题是,具体类在 CallOriginalMethod() 行上被调用,我希望在调用 Stub.GetAccounts() 时在重放期间调用该类。 因此,在录制期间以及在执行测试时,当我只是想模拟它们时,就会调用实现的具体方法 - 部分正如我所解释的那样。 这是我的误解吗? 我是否应该无法模拟/存根具体类和接口?
我是否需要将 virtual 关键字添加到我想要模拟的方法中?
这可能吗? 我该怎么做呢?
I am new to unittesting and mocking in general and am trying to set up tests for one of my classes where I want to make sure that a particular method is called from another method within the same class. I would therefore like to use the concrete implementation but mock out parts of it. Is this possible?
public class MyClass { public Accounts[] GetAccounts() { return GetAccounts(null); } public Accounts[] GetAccounts(CustomerId id) { if(id == null) { // Get all accounts } } }
I therefore am trying to set up a stub that will get GetAccounts() called (which I want to use the concrete implementation) but I would like to check if that method calls GetAccounts(null).
[Test] public void GetAccountsTest() { MockRepository mocks = new MockRepository(); MyClass stub = mocks.Stub(); using(mocks.Record()) { Expect.Call(() => stub.GetAccounts()).CallOriginalMethod(); Expect.Call(() => stub.GetAccounts(null)); } mocks.ReplayAll(); stub.GetAccounts(); mocks.VerifyAll(); }
Problem is that the concrete class gets called on the CallOriginalMethod() line which I am expecting to get called during the replay when I call stub.GetAccounts().
So both during the recording as well as when I am performing the tests the concrete methods of the implementation are called when I simply want to mock them out - well partially as I have explained. Is this a misunderstanding on my part? Should I not be able to mock/stub concrete classes as well as interfaces?
Do I need to add virtual keyword to the methods I want to be able to mock out?
Is this even possible? How would I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您可能想使用 PartialMock。 它将允许您模拟虚拟方法。
Looks like you might want to use a PartialMock. It will allow you to mock virtual methods.