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

Testing non virtual public methods #1303

Closed
carzaza opened this issue Nov 30, 2022 · 1 comment
Closed

Testing non virtual public methods #1303

carzaza opened this issue Nov 30, 2022 · 1 comment

Comments

@carzaza
Copy link

carzaza commented Nov 30, 2022

Hello,

I'm trying to unit test a public class that contains an orchestrator method and a series of methods, which can be called by the orchestrator but also externally:

public class ClassForTesting
{
    public void MethodA()
    {
        this.MethodA();

        this.MethodB();
    }

    public void MethodB()
    {
        // Do some stuff.
    }

    public void MethodC()
    {
        // Do some stuff.
    }
}

My intention is to perform a test like the following one, but it can not be done without virtual methods:

// Arrange.
Mock<ClassForTesting> classForTestingMock = new Mock<ClassForTesting>()
{
    CallBase = true,
};

classForTestingMock.Setup(m => m.MethodB());
classForTestingMock.Setup(m => m.MethodC());

// Act.
classForTestingMock.Object.MethodA();

// Assert.
classForTestingMock.Verify(m => m.MethodB(), Times.Once());
classForTestingMock.Verify(m => m.MethodC(), Times.Once());
classForTestingMock.VerifyNoOtherCalls();

Is there any alternative for testing this? Does any approach exist that I am not considering?

I have searched across Stack Overflow and the only alternative is using other frameworks, this is the reason why I am asking this directly in your github instead of in SO.

Thanks in advance

@stakx
Copy link
Contributor

stakx commented Dec 1, 2022

AFAIK, the only tools that can intercept/replace non-overridable methods are those based on the .NET runtime's unmanaged profiling API (and Moq isn't one of those). So yes, either use a different mocking library, or change your code so it is more easily testable.

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

No branches or pull requests

2 participants