簡體   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