Rhino-Mocking ExpectationViolationException

- 此内容更新于:2015-01-06


I started to use Rhino-Mocks and Unit-Tests a few days ago so I'm new in this.

I created a disposable class like this:

public class SomeClass : IDisposable
    private bool _disposed;

    public SomeOtherClass ObjB { get; private set; }

    public SomeClass(SomeOtherClass b)
        ObjB = b;

    public void Dispose()

    protected virtual void Dispose(bool disposing)
        if (_disposed)

        if (disposing)
            // set all properties to null

            ObjB = null;
            // ...

        _disposed = true;

and the unit test which should check if the dispose was done correctly:

public class SomeClassTests
    public void ShouldDisposeCorrectly()
        var classB = MockRepository.GenerateStrictMock<SomeOtherClass>()
        SomeClass smth;

        using (smth = MockRepository.GenerateStrictMock<SomeClass>(classB))
        { }

        smth.Expect(p => p.ObjB).Should().BeNull();

Now when I start the test it throws the following error: Rhino.Mocks.Exceptions.ExpectationViolationException : SomeClass.Dispose(True); Expected #0, Actual #1.

Can you help me to find the missing step? :-)


What are you actually wanting to test here?

That the compiler produces the correct code when you use a using statement? Seems fairly pointeless.

Or that your class implements IDisposable? You could do that with a simpler test.

Or that your disposal routine correctly disposes of the resources? This test doesn't check that. You could completely empty the Dispose(bool) method and the test you say you want to write would still pass.

Better to check that ObjB is null after the object has been disposed and that any other things which should be done in the dispose method have been. What you want to check is that the behaviour when you dispose your object is what you expect

tkutter的回复:谢谢你的快速回答。你是对的,这# 39;年代更好的实现检查对象是null。不幸的是,同样的信息出现在这个版本…我# 39;已经编辑了Unittest参与我的问题。

(原文:Thanks for your fast answer. You are right, it's better to implement a check if the object would be null. Unfortunately the same message appears in this version... I've edited the Unittest part in my question.)

Sam Holder的回复:不,我认为你只需要使用一个严格的模拟,而是使用一个动态模拟,获得# 39;t抱怨缺乏明确的设置。看到这个问题和答案

(原文:I think you just need to not use a strict mock and instead use a dynamic mock, which won't complain at the lack of explicit setup. See this question and answer)


(原文:Thanks! It works now!)