简体   繁体   中英

How to Mock Base Class Property or Method in C#

i surf over internet for mock base class member in Nunit test case with no luck and finally decide to ask this scrap to stack overflow community.

Below code snippet has scenario in my application. i am going to write unit test for BankIntegrationController class and i want to make stub data or make mock for IsValid property and Print method.

Fremwork : Moq,Nunit

public class CController : IController
{
     public bool IsValid {get;set;}

     public string Print()
     {
            return  // some stuff here;
     }
}

public class BankIntegrationController : CController, IBankIntegration
{
    public object Show()
    {
       if(this.IsValid)
       {
          var somevar = this.Print();
       }

       return; //some object
    }
}

You don't need to mock anything. Just set the property before calling Show :

[Fact]
public void Show_Valid()
{
    var controller = new BankIntegrationController { Valid = true };
    // Any other set up here...
    var result = controller.Show();
    // Assertions about the result
}

[Fact]
public void Show_Invalid()
{
    var controller = new BankIntegrationController { Valid = false };
    // Any other set up here...
    var result = controller.Show();
    // Assertions about the result
}

Mocking is a really valuable technique when you want to specify how a dependency would behave in a particular scenario (and particularly when you want to validate how your code interacts with it), but in this situation you don't have any dependencies (that you've shown us). I've observed a lot of developers reaching for mocks unnecessarily, in three situations:

  • When there's no dependency (or other abstract behaviour) involved, like this case
  • When a hand-written fake implementation would lead to simpler tests
  • When an existing concrete implementation would be easier to use. (For example, you'd rarely need to mock IList<T> - just pass in a List<T> in your tests.)

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