【问题标题】:RhinoMocks AssertWasCalled on mocked object's method that needs to have an object returned?RhinoMocks AssertWasCalled 在需要返回对象的模拟对象方法上?
【发布时间】: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


    【解决方案1】:

    您可以在模拟对象上设置一个期望,该方法与返回值一起被调用:

    MappedSomething fakeMappedSomething = //whatever
    mapper.Expect(m => m.Map(something)).Return(fakeMappedSomething);
    ...
    sut.SomeMethod(_someListOfSomethings);
    

    然后在测试结束时验证预期。

    【讨论】:

    • 与往常一样,这是我尝试但未能以某种方式准确实施的明显第一个解决方案。再试一次,我们是金子。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多