Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invocation on a non-virtual method when object casted to interface is wrong #156

Closed
kostadinmarinov opened this issue Feb 17, 2015 · 2 comments
Labels

Comments

@kostadinmarinov
Copy link
Contributor

This is a problem only in master. In release v4.2.1312 it's not met.

You have a concrete class which implements an interface.The interface's members are implemented as NON-VIRTUAL in the concrete class. Then you create a mock of the concrete class. If the mock's object is passed as the concrete class, there is no problem to call the method - its concrete implementation is used. However, if you pass the object as the interface, then the method invocation is mocked and doesn't use the concrete implementation.

However, this behavior is unexpected when the original mock was created on the concrete type, it should work based on its interface not as it's used.

The problem is reproducible with the following code:

public class A : IA
{
public void Foo()
{
Debug.WriteLine("Foo() called.");
}
}

public interface IA
{
    void Foo();
}

[TestFixture]
public class TestFixture
{
    [Test]
    public void Test()
    {
        Mock<A> mock = new Mock<A>(MockBehavior.Strict);

        mock.Object.Foo();
        ((IA)mock.Object).Foo();    // throws  Moq.MockException : IX.Foo() invocation failed with mock behavior Strict.
    }
}
@delta-emil
Copy link

delta-emil commented May 3, 2016

FYI: This was caused by commit 162a543
However, undoing that change breaks test ShouldBeAbleToCastToImplementedInterface

@stakx
Copy link
Contributor

stakx commented Jun 20, 2017

Fixed in Moq 4.7.58.

@stakx stakx closed this as completed Jun 20, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants