如何在C#中模拟基类属性或方法

问题描述 投票:1回答:2

我在Nunit测试案例中通过互联网浏览模拟基类成员而没有运气,最后决定要求这个废料堆栈溢出社区。

下面的代码片段在我的应用程序中有方案。我将为BankIntegrationController类编写单元测试,我想制作存根数据或为IsValid属性和Print方法进行模拟。

框架:Mock,Nuneet

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
    }
}
c# mocking nunit moq
2个回答
1
投票

你不需要模仿任何东西。只需在调用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
}

当您想要指定依赖在特定场景中的行为方式时(特别是当您想要验证代码与其交互的方式时)时,模拟是一种非常有价值的技术,但在这种情况下,您没有任何依赖关系(即已经向我们展示了。在三种情况下,我观​​察到很多开发人员不必要地进行模拟攻击:

  • 当没有涉及依赖(或其他抽象行为)时,就像这种情况一样
  • 当手写的虚假实现会导致更简单的测试
  • 当现有的具体实现更容易使用时。 (例如,您很少需要模拟IList<T> - 只需在测试中传入List<T>。)

-1
投票

假设您的IsValid属性是IController接口的一部分,您可以使用Moq多个接口,如下所示:

var bankController = new Mock<IBankIntegration>();
var cController = cController.As<IController>();
cController.SetupGet(m => m.IsValid).Returns(true);

这包括在Miscellaneous section of the Moq Quick Start中。

© www.soinside.com 2019 - 2024. All rights reserved.