问题描述:

Is it possible to mock a function call with NUnit? I know the standard answer here is extract an interface and use dependency injection, but I want to know if it is even possible to not do that and just mock a function call.

网友答案:

Probably not, without an interface etc.

Without interfacing, you might need to resort to Microsoft Fakes (Shims) to mock a method call as is. (and it can get dicey with generation of Fakes assemblies)

Fakes works well when you have a method like

public DateTime GetCurrentUtcDate()
{
 return DateTime.UtcNow;
}

and you want to run an unit test involving code which calls this method. we don't generally think of interfaces/DI for such methods.. Fakes comes handy for such cases.

网友答案:

Sometimes it is useful to stub function of the class that is undertest with a proxy class. I hope I understatnd you correctly and the example above would help:

class SomeClass
{
    public void SomeMethod()
    {
         /* SomeCode */

         if (SomeCheck())
         {           
             /* Another Code */
         }
    }

    protected virtual bool SomeCheck()
    {
        /* Some code*/
    }
}

And in test class you declare a proxy class derived from SomeClass and implement a property with a help of which you will be able to control the behaviour of SomeCheck() method (or leave its "base" behaviour):

class SomeClassProxy : SomeClass
{
    public bool? StubSomeCheckValue { get; set; }

    protected override bool SomeCheck()
    {
        if (!StubSomeCheckValue.HasValue)
        {
            return base.SomeCheck();
        }

        return StubSomeCheckValue.Value;
    }
}

Now while testing SomeMethod() of the SomeClass you instantiate SomeClassProxy:

[Test]
public void SomeMethod_WhenSomeCheckIsTrue_ExpectedResult()
{
    _sut = new SomeClassProxy();

    _sut.StubSomeCheckValue = true;

    _sut.SomeMethod();

    /* Assertions */
}
相关阅读:
Top