使用MOQ控制器内部的模拟类方法

时间:2011-07-21 20:08:12

标签: c# unit-testing moq

使用下面的示例代码,我如何使用MOQ来模拟(引用的dll)类方法

    [TestMethod]
    public void SampleTestMethod()
    {
        var _controller = new MyController();

        var stub = new Mock<class1>();
        stub.Setup(x => x.DoSomething(It.IsAny<int>())).Returns(2);
        //var retval = stub.Object.DoSomething();

        var result = _controller.MyAction() as ViewResult;
        stub.Verify(x => x.DoSomething(It.IsAny<int>()), Times.AtLeastOnce(), "Didn't call DoSomething");
    }//end test


//Controller
public class MyController{
 public MyController(){}

 public virtual ActionResult MyAction(){
  var ret = new class1();
  var result = ret.DoSomething(10);

  //rest of code  

  return View();

 }

}

//external class
public class class1
{
        public virtual int DoSomething(int i)
        {
            return 1;
        }
}

1 个答案:

答案 0 :(得分:2)

您需要将外部类'class1'的实例注入控制器的构造函数中。然后你可以使用Moq来模拟它并注入假的。像这样:

public class MyController{
    private readonly IClass1 _class1;
    public MyController(IClass1 class1){
        _class1 = class1;
    }
    // Other code uses this private instance
}

[TestMethod]
public void Test(){
    var class1 = new Mock<Class1>();
    var controller = new MyController(class1.Object);
}