RhinoMocks AssertWasCalled模拟对象的方法需要返回一个对象吗?
问题描述:
使用RhinoMocks,我有一个catch-22的情况:我想验证一个方法是否被调用,但是这个方法需要返回一个对象,因为返回的对象是在下一行执行的。换句话说,在接口上嘲讽返回一个空值,但不嘲笑它并不能让我以任何方式来验证该方法是否从某种集成测试中被调用。RhinoMocks AssertWasCalled模拟对象的方法需要返回一个对象吗?
因此,看下面我投掷在一起的人为样本,有没有办法做我想要的?我认为可能有办法将AssertWasCalled方法设置为实际返回某个方法的桩时,但是......感谢任何指针(特别是如果它只是一个应该解决的设计缺陷)。
public class SomeClass
{
private readonly ISomeMapper _someMapper;
[Inject]
public Test(ISomeMapper someMapper)
{
_someMapper = someMapper;
}
public SomeReturnType SomeMethod(IEnumerable<ISomethingToMap> somethings)
{
//foreach over somethings and do something based on various properties for each
MappedSomething mappedSomething = _someMapper.Map(something); // AssertWasCalled here
mappedSomething.SomeProperty = somethingFromSomewhere; // Which gets a null reference exception here (understandably) if _someMapper is mocked
//end foreach after more stuff
}
}
///...
[Test]
public void the_mapper_should_be_called()
{
//If mock or stub, then can AssertWasCalled, but then only null object returned.
// If don't mock, then cannot assert whether was called.
var mapper = MockRepository.GenerateStub<ISomeMapper>();
var somethingToMap = _someListOfSomethings[0];
var sut = new SomeClass(mapper);
sut.SomeMethod(_someListOfSomethings);
mapper.AssertWasCalled(x => x.Map(somethingToMap));
}
答
您可以设置模拟对象上的期望,方法与返回值一起叫:
MappedSomething fakeMappedSomething = //whatever
mapper.Expect(m => m.Map(something)).Return(fakeMappedSomething);
...
sut.SomeMethod(_someListOfSomethings);
然后,确认在测试结束时的预期。
像往常一样,它似乎是我尝试的第一个明显的解决方案,但未能以某种方式准确实施。再试一次,我们是黄金。谢谢! – Ted 2010-01-07 23:50:20