【发布时间】:2011-01-02 17:27:10
【问题描述】:
使用 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));
}
【问题讨论】:
标签: c# unit-testing rhino-mocks