Using moq to mock only some methods

前端 未结 3 968
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 07:00

I have the following method:

public CustomObect MyMethod()
{
    var lUser = GetCurrentUser();
    if (lUser.HaveAccess)
    {
        //One behavior
    }
          


        
相关标签:
3条回答
  • 2020-12-01 07:34

    I had a similar case. I found the following code gave me more flexibility to use both mocked methods and actual methods from some specific implementation of an interface:

    var mock = new Mock<ITestClass>(); // Create Mock of interface
    
    // Create instance of ITestClass implementation you want to use
    var inst = new ActualTestClass();
    
    // Setup to call method of an actual instance
    // if method returns void use mock.Setup(...).Callback(...)
    mock.Setup(m => m.SomeMethod(It.IsAny<int>())
        .Returns((int x) => inst.SomeMethod(x));
    

    Now you can use the actual method but also use things like Verify to see how many times it has been called.

    0 讨论(0)
  • 2020-12-01 07:41

    Expanding on lee's answer,

    You do not need to make all of the methods and properties on your class virtual, only the ones you wish to mock.

    Also, it should be noted that you should be mocking the concrete implementation of your class.

    var mock = new Mock<YourTestClass>(); // vs. var mock = new Mock<IYourTestInterface>();

    If your class does not have a default constructor, you will also need to specify arguments to pass in to it via:

    var mock = new Mock<YourTestClass>(x, y, z);
    // or
    var mock = new Mock<YourTestClass>(MockBehavior.Default, x, y, z);
    

    Where x, y, z are the first, second, and third parameters to your constructor respectively.

    And lastly, if the method you are looking to mock is protected you will need to include Moq.Protected

    using Moq.Protected;
    
    TReturnType returnValue = default(TReturnType);
    
    mock.Protected()
        .Setup<TReturnType>("YourMockMethodName", It.IsAny<int>()) // methodname followed by arguments
        .Returns(returnValue);
    
    0 讨论(0)
  • 2020-12-01 07:45

    This is called a partial mock and the way I know to do it in moq requires mocking the class rather than the interface and then setting the "Callbase" property on your mocked object to "true".

    This will require making all the methods and properties of the class you are testing virtual. Assuming this isn't a problem, you can then write a test like this:

     var mock = new Mock<YourTestClass>();
     mock.CallBase = true;
     mock.Setup(x => x.GetCurrentUser()).Returns(lUnauthorizedUser);
     mockedTest.Object.MyMethod();
    
    0 讨论(0)
提交回复
热议问题