使用RhinoMocks,我有一个catch-22情况:我想验证是否调用了一个方法,但是这个方法需要在其上返回一个对象,因为返回的对象在下一行中被操作。换句话说,在接口上进行模拟只返回一个空值,但是没有模拟它并没有给我任何方法来验证该方法是否被某种集成测试所调用。
因此,看看下面的人工样本,我有没有办法做我想做的事情?我认为可能有一种方法可以设置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));
}
答案 0 :(得分:2)
您可以在模拟对象上设置调用该方法的期望值以及返回值:
MappedSomething fakeMappedSomething = //whatever
mapper.Expect(m => m.Map(something)).Return(fakeMappedSomething);
...
sut.SomeMethod(_someListOfSomethings);
然后在测试结束时验证期望值。