如何为依赖项注入服务.net核心编写NUnit测试

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

我有一个带有一些已注入服务的服务类(图像01)。我需要为该类编写NUnit测试。我是NUnit的新手,正在努力使该对象成为我的AzureService.cs

图片01enter image description here

这是我的考试课程

using JohnMorris.Plugin.Image.Upload.Azure.Services;
using Nop.Core.Caching;
using Nop.Core.Domain.Media;
using Nop.Services.Tests;
using NUnit.Framework;

namespace JohnMorris.Plugin.Image.Upload.Azure.Test
{
    public class AzureServiceTest 
    {
        private AzureService _azureService;

        [SetUp]
        public void Setup()
        {
               _azureService = new AzureService( cacheManager,  mediaSettings,  config,  logger);
        }      

        [Test]
        public void App_settings_has_azure_connection_details()
        {
           var url= _azureService.GetAzureStorageUrl();
            Assert.IsNotNull(url);
            Assert.IsNotEmpty(url);
        }
    }
}
nunit asp.net-core-2.1
1个回答
0
投票

问题是,您到底想测试什么?如果要测试NopConfig是否从AppSettings正确读取值,则根本不需要测试AzureService

[如果要测试GetAzureStorageUrl方法是否正常工作,则应模拟NopConfig依赖项,并专注于仅测试AzureService方法,如下所示:

using Moq;
using Nop.Core.Configuration;
using NUnit.Framework;

namespace NopTest
{
    public class AzureService
    {
        private readonly NopConfig _config;

        public AzureService(NopConfig config)
        {
            _config = config;
        }

        public string GetAzureStorageUrl()
        {
            return $"{_config.AzureBlobStorageEndPoint}{_config.AzureBlobStorageContainerName}";
        }
    }

    [TestFixture]
    public class NopTest
    {
        [Test]
        public void GetStorageUrlTest()
        {
            Mock<NopConfig> nopConfigMock = new Mock<NopConfig>();

            nopConfigMock.Setup(x => x.AzureBlobStorageEndPoint).Returns("https://www.example.com/");
            nopConfigMock.Setup(x => x.AzureBlobStorageContainerName).Returns("containername");

            AzureService azureService = new AzureService(nopConfigMock.Object);

            string azureStorageUrl = azureService.GetAzureStorageUrl();

            Assert.AreEqual("https://www.example.com/containername", azureStorageUrl);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.