如何为依赖注入服务.net内核编写NUnit测试
我有一个带有一些注入服务的服务类。它正在处理我的Azure存储请求。我需要为那个类编写NUnit测试。 我是NUnit的新手,我正在努力使它成为我的AzureService.cs 下面是AzureService.cs。我使用了一些注入式服务如何为依赖注入服务.net内核编写NUnit测试,nunit,asp.net-core-2.1,Nunit,Asp.net Core 2.1,我有一个带有一些注入服务的服务类。它正在处理我的Azure存储请求。我需要为那个类编写NUnit测试。 我是NUnit的新手,我正在努力使它成为我的AzureService.cs 下面是AzureService.cs。我使用了一些注入式服务 using System; using System.Linq; using System.Threading.Tasks; using JohnMorris.Plugin.Image.Upload.Azure.Interfaces; using Micro
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
}
}
问题是,你们到底想测试什么?如果要测试
NopConfig
是否正确读取AppSettings中的值,则根本不必测试AzureService
如果您想测试GetAzureStorageUrl
方法是否正常工作,那么您应该模拟NopConfig
依赖关系,只测试AzureService
方法,如下所示:
使用Moq;
使用Nop.Core.Configuration;
使用NUnit.Framework;
名称空间NopTest
{
公共级AzureService
{
私有只读NopConfig _config;
公共AzureService(NopConfig配置)
{
_config=config;
}
公共字符串GetAzureStorageUrl()
{
返回$“{{u config.AzureBlobStorageEndPoint}{{u config.AzureBlobStorageContainerName}”;
}
}
[测试夹具]
公共类测试
{
[测试]
public void GetStorageUrlTest()
{
Mock nopConfigMock=新建Mock();
nopConfigMock.Setup(x=>x.AzureBlobStorageEndPoint)。返回(“https://www.example.com/");
nopConfigMock.Setup(x=>x.AzureBlobStorageContainerName).Returns(“containername”);
AzureService AzureService=新的AzureService(nopConfigMock.Object);
字符串azureStorageUrl=azureService.GetAzureStorageUrl();
Assert.AreEqual(“https://www.example.com/containername“,azureStorageUrl);
}
}
}
App\u settings\u has\u azure\u connection\u details()只是一个测试查询。我用更多的细节编辑了我的问题
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
}
}
}