简体   繁体   English

单元测试C#MOQ依赖注入

[英]Unit Test C# MOQ dependecy injection

I am new to Unit test. 我是单元测试的新手。 Trying to integrate unit test for legacy code. 尝试为遗留代码集成单元测试。 To moq the same method of the class, do i need to inject the interface or is there any other option.?? 要最小化该类的相同方法,我需要注入接口还是有其他选择。

If interface injection to the constructor is the only way, how to define the default constructor for the existing code. 如果将接口注入构造函数是唯一的方法,则如何为现有代码定义默认构造函数。 Example: 例:

    private IController _iController;
    public Controller(IController iController)
    {
        _iController= iController;

    } 
    public ActionResult ActualMethod()
    { 
        _iController.FillViewBag(); 
        return View();
    }
    public void UnitTest()
    {
       var i = new Mock<IController>();
        i.Setup(d => d.FillViewBag());
        var controller = new Controller(i.Object); 
        controller.ActualMethod();
    }

For the above code i am able to perform unit test. 对于上面的代码,我能够执行单元测试。 But if i browse the method(manually test the action) it is failing object ref not set. 但是,如果我浏览该方法(手动测试操作),则会失败,未设置对象引用。 as the object is empty. 因为对象是空的。 How to fix this issue? 如何解决这个问题?

Also i am using FillViewBag in many places, those place i dont want to change the call based on interface for now. 我也在很多地方使用FillViewBag,那些地方我现在不想基于接口更改呼叫。 Please advise. 请指教。

You mock the IController interface and then pass the mocked object into your constructor. 您可以模拟IController接口,然后将模拟对象传递到构造函数中。

var mockController = new Mock<IController>();

var controller = new Controller(mockController.Object);

You also need to setup what you want the mocked FillViewBag to do: 您还需要设置要让模拟的FillViewBag执行的操作:

var mockController.Setup(c => c.FillViewBag).Callback(() => do something here);

Plenty of info for this in the Moq Quickstart Moq 快速入门中的大量信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM