繁体   English   中英

如何模拟构造函数内部的依赖关系?

[英]How to mock the dependency inside constructor?

I need to test the function GetPollData() and i have written Apitest class and created mock object of that class and created a test method TestGetPollData() that will check the return value and expected value are
是否相等。但我得到的返回值为 20 而不是预期的 10。我调试并检查了在 API 中创建的业务 object
class 构造函数未被模拟,并且该依赖项返回在 class 中初始化的值,而不是我想返回的模拟值。有什么方法可以模拟 object 或使 Atest 在构造函数中按预期工作。我正在使用 nunit 框架进行测试。 请告诉我我做错了什么以及我应该怎么做?

 public class API
     {  
        public Business business { get; set; }

        public API()
        {
           business=new Business();
        }

        public int GetPollData()
        {
           return business.polltime();
        }
      }

 public class Business
   {
        public int polltime()
        {
        return Service.poll;
        }
   }    

 public class Service
    {
    public int poll=20;
    }

//API TEST CLASS
 public class Apitest
     {
        private Mock<API> api = new Mock<API>();
        API ApiObj = new ApiObj();

        // Testing the GetPollData method 
        public TestGetPollData()
          {
           api.Setup( x => x.GetPollData()).Returns(10);
           int value=ApiObj.GetPollData();
           Assert.AreEqual(10,value);
          }
       }

使用 Moq 可以模拟的内容是有限制的。 此处将对此进行更详细的介绍。

我可以使用 moq Mock<MyClass> 来模拟 class,而不是接口吗?

将 Moq 与接口或至少抽象 class 一起使用更为常见。

我已经重构了您的代码,以便 API 实现接口 IAPI。 然后模拟 IAPI。

我已经更改了您的测试方法,以便您从模拟的 object 而不是真正的 object 调用 GetPollData() 方法。

它还建议将您对业务 class 的依赖注入到 API 的构造函数中,以便以后可以在需要时进行模拟。 我会让你这样做。

using Moq;
using NUnit.Framework;

namespace EntitlementServer.Core.Tests
{
    public interface IAPI
    {
        int GetPollData();
    }

    public class API : IAPI
    {
        public Business business { get; set; }

        public API()
        {
            business = new Business();
        }

        public int GetPollData()
        {
            return 20;
        }
    }

    public class Business
    {
        public int polltime()
        {
            return Service.poll;
        }
    }

    public static class Service
    {
        public static int poll = 20;
    }

    [TestFixture]
    public class Apitest
    {
        // Testing the GetPollData method 
        [Test]
        public void TestGetPollData()
        {
            var api = new Mock<IAPI>();
            api.Setup(x => x.GetPollData()).Returns(10);
            int value = api.Object.GetPollData();

            Assert.AreEqual(10, value);
        }
    }
}

您必须通过注入依赖项来重构它。

public class API { 
    public Business business { get; set; }

    public API( Business b )
    {
       business= b;
    }

    public int GetPollData()
    {
       return business.polltime();
    }
 }

在测试中,将你的模拟Business传递给 API,并测试模拟实例的polltime是否被调用。

暂无
暂无

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

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