简体   繁体   中英

How to test a method on a service, while mocking another on the same service?

Say I have a service:

UserService

And it has 2 public methods:

Method1, Method2

And I'm testing Method1, but Method1 makes a call to Method2.

How can I mock (or stub is the more correct word) the call to Method2.

If I mock UserService, that I can't actually test Method1 now can I?

This cannot be done unless you weaken the coupling between those methods, probably by introducing abstractions/interfaces. Your current implementation of UserService implies a strong coupling between Method1 and Method2.

If I understand your question correctly, you can use CallBase :

Invoke base class implementation if no expectation overrides the member (aka "Partial Mocks" in Rhino Mocks)

Create your mock with CallBase = true , setup Method2 to return whatever value you want to test with, and then call Method1 .

As an example:

class Program
{
    static void Main(string[] args)
    {
        var mock = new Mock<UserService> { CallBase = true };
        mock.Setup(m => m.Method2()).Returns("Mock 2");

        Console.WriteLine(mock.Object.Method1());
        Console.ReadLine();
    }
}

public class UserService
{
    public virtual string Method1()
    {
        return "Method 1 :: " + Method2();
    }

    public virtual string Method2()
    {
        return "Method 2";
    }
}

I'm still struggling with the question, " Should I mock the call to Method2?" I'm inclined to say, "No." If the class internally uses both methods as part of its logic, then both are part of the test. Mocks are for dependencies on UserService , not internal implementation details.

In short, while I'm not aware of any mocking tools which can do this, I don't think it should be done in the first place.

You can't with Moq. You could look into using Moles, which does give that kind of granularity. If you Mole your own assembly, you can mock at the method/property level rather than at the class/interface level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM