断言一个方法只被调用一次 [英] Asserting that a method is called exactly one time
本文介绍了断言一个方法只被调用一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想断言一个方法只被调用一次.我使用的是 RhinoMocks 3.5.
I want to assert that a method is called exactly one time. I'm using RhinoMocks 3.5.
以下是我认为可行的方法:
Here's what I thought would work:
[Test]
public void just_once()
{
var key = "id_of_something";
var source = MockRepository.GenerateStub<ISomeDataSource>();
source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))
.Return(new Something())
.Repeat.Once();
var client = new Client(soure);
// the first call I expect the client to use the source
client.GetMeMyThing(key);
// the second call the result should be cached
// and source is not used
client.GetMeMyThing(key);
}
如果 GetMeMyThing()
的第二次调用调用 source.GetSomethingThatTakesALotOfResources()
,我希望这个测试失败.
I want this test to fail if the second invocation of GetMeMyThing()
calls source.GetSomethingThatTakesALotOfResources()
.
推荐答案
这是我验证方法被调用一次的方法.
Here's how I'd verify a method is called once.
[Test]
public void just_once()
{
// Arrange (Important to GenerateMock not GenerateStub)
var a = MockRepository.GenerateMock<ISomeDataSource>();
a.Expect(x => x.GetSomethingThatTakesALotOfResources()).Return(new Something()).Repeat.Once();
// Act
// First invocation should call GetSomethingThatTakesALotOfResources
a.GetMeMyThing();
// Second invocation should return cached result
a.GetMeMyThing();
// Assert
a.VerifyAllExpectations();
}
这篇关于断言一个方法只被调用一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文