【问题标题】:How to write NUnit test for dependency injection service .net core如何为依赖注入服务.net核心编写NUnit测试
【发布时间】:2020-04-12 21:06:59
【问题描述】:

我有一个带有一些注入服务的服务类。它正在处理我的 Azure 存储请求。我需要为该类编写 NUnit 测试。 我是 NUnit 的新手,我正在努力制作我的 AzureService.cs 的对象

在 AzureService.cs 下。我使用了一些注入服务

using System;
using System.Linq;
using System.Threading.Tasks;
using JohnMorris.Plugin.Image.Upload.Azure.Interfaces;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Nop.Core.Caching;
using Nop.Core.Configuration;
using Nop.Core.Domain.Media;
using Nop.Services.Logging;

namespace JohnMorris.Plugin.Image.Upload.Azure.Services
{
    public class AzureService : IAzureService
    {

        #region Constants

        private const string THUMB_EXISTS_KEY = "Nop.azure.thumb.exists-{0}";
        private const string THUMBS_PATTERN_KEY = "Nop.azure.thumb";

        #endregion

        #region Fields
        private readonly ILogger _logger;
        private static CloudBlobContainer _container;
        private readonly IStaticCacheManager _cacheManager;
        private readonly MediaSettings _mediaSettings;
        private readonly NopConfig _config;

        #endregion

        #region
        public AzureService(IStaticCacheManager cacheManager, MediaSettings mediaSettings, NopConfig config, ILogger logger)
        {
            this._cacheManager = cacheManager;
            this._mediaSettings = mediaSettings;
            this._config = config;
            this._logger = logger;
        }

        #endregion


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

        public virtual async Task DeleteFileAsync(string prefix)
        {
            try
            {
                BlobContinuationToken continuationToken = null;
                do
                {                    
                    var resultSegment = await _container.ListBlobsSegmentedAsync(prefix, true, BlobListingDetails.All, null, continuationToken, null, null);

                   await Task.WhenAll(resultSegment.Results.Select(blobItem => ((CloudBlockBlob)blobItem).DeleteAsync()));

                    //get the continuation token.
                    continuationToken = resultSegment.ContinuationToken;
                }
                while (continuationToken != null);

                _cacheManager.RemoveByPrefix(THUMBS_PATTERN_KEY);
            }
            catch (Exception e)
            {
                _logger.Error($"Azure file delete error", e);
            }
        }


        public virtual async Task<bool> CheckFileExistsAsync(string filePath)
        {
            try
            {
                var key = string.Format(THUMB_EXISTS_KEY, filePath);
                return await _cacheManager.Get(key, async () =>
                {
                    //GetBlockBlobReference doesn't need to be async since it doesn't contact the server yet
                    var blockBlob = _container.GetBlockBlobReference(filePath);

                    return await blockBlob.ExistsAsync();
                });
            }
            catch { return false; }
        }

        public virtual async Task SaveFileAsync(string filePath, string mimeType, byte[] binary)
        {
            try
            {
                var blockBlob = _container.GetBlockBlobReference(filePath);

                if (!string.IsNullOrEmpty(mimeType))
                    blockBlob.Properties.ContentType = mimeType;

                if (!string.IsNullOrEmpty(_mediaSettings.AzureCacheControlHeader))
                    blockBlob.Properties.CacheControl = _mediaSettings.AzureCacheControlHeader;

                await blockBlob.UploadFromByteArrayAsync(binary, 0, binary.Length);

                _cacheManager.RemoveByPrefix(THUMBS_PATTERN_KEY);
            }
            catch (Exception e)
            {
                _logger.Error($"Azure file upload error", e);
            }
        }

        public virtual byte[] LoadFileFromAzure(string filePath)
        {
            try
            {
                var blob = _container.GetBlockBlobReference(filePath);
                if (blob.ExistsAsync().GetAwaiter().GetResult())
                {
                    blob.FetchAttributesAsync().GetAwaiter().GetResult();
                    var bytes = new byte[blob.Properties.Length];
                    blob.DownloadToByteArrayAsync(bytes, 0).GetAwaiter().GetResult();
                    return bytes;
                }
            }
            catch (Exception)
            {
            }
            return new byte[0];
        }
        #endregion
    }
}

这是我下面的测试类,我需要创建 new AzureService();从我的服务班。但是在我的 AzureService 构造函数中,我正在注入一些服务

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);
        }

       [Test]
       public void Check_File_Exists_Async_test(){
           //To Do
       }

       [Test]
       public void Save_File_Async_Test()(){
           //To Do
       }

       [Test]
       public void Load_File_From_Azure_Test(){
           //To Do
       }
    }
}

【问题讨论】:

    标签: nunit asp.net-core-2.1


    【解决方案1】:

    问题是,您到底想测试什么?如果您想测试 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);
            }
        }
    }
    

    【讨论】:

    • App_settings_has_azure_connection_details() 只是一个测试查询。我用更多细节编辑了我的问题
    猜你喜欢
    • 2020-01-17
    • 2018-12-14
    • 2019-01-31
    • 2018-09-17
    • 2019-02-16
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多