我正在尝试对将文件上传到Azure Blob存储的类进行单元测试。上传方法以CloudBlobContainer
为输入。调用_storageContainer.Object.GetBlockBlobReference()
时,抛出System.NullReferenceException。任何人都可以帮我嘲笑这个吗?
单元代码:
[TestClass()]
public class BlobStorageServiceUploadUnitTest
{
private static BlobStorageService _service;
private static Mock<CloudBlobContainer> _storageContainer;
private static List<FileType> _extensions;
private static int _maxSize;
[ClassInitialize]
public static void Setup_Service(TestContext context)
{
_extensions = new List<FileType> { FileType.Image };
_maxSize = 2048;
_storageContainer = new Mock<CloudBlobContainer>();
_service = new BlobStorageService(new Mock<BEntitiesContainer>().Object, _storageContainer.Object);
}
[TestMethod()]
public void When_FileIsDeleted()
{
var file = CreateMockFile("test.jpg", 500000);
var blob = _storageContainer.Object.GetBlockBlobReference("deleteTest.jpg");
blob.UploadFromStream(file.Object.InputStream);
_service.DeleteFromStorage("deleteTest.jpg");
var blobs = _storageContainer.Object.ListBlobs();
Assert.AreEqual(0, blobs.Count());
}
public Mock<HttpPostedFileBase> CreateMockFile(string fileName, int sizeInBytes)
{
var file = new Mock<HttpPostedFileBase>();
var stream = new MemoryStream();
var bmp = new Bitmap(1, 1);
var graphics = Graphics.FromImage(bmp);
graphics.FillRectangle(Brushes.Black, 0, 0, 1, 1);
bmp.Save(stream, ImageFormat.Jpeg);
file.Setup(pf => pf.InputStream).Returns(stream);
file.Setup(f => f.FileName).Returns(fileName);
file.Setup(f => f.ContentLength).Returns(sizeInBytes);
return file;
}
}
经过测试的课程:
public class BlobStorageService : BaseRepository<User>
{
private CloudBlobContainer _storageContainer;
public BlobStorageService(BEntitiesContainer context, CloudBlobContainer storageContainer) : base(context)
{
Context = context;
_storageContainer = storageContainer;
}
public void DeleteFromStorage(string fileName)
{
_storageContainer.GetBlockBlobReference(fileName).DeleteIfExists();
}
}
答案 0 :(得分:1)
您只能做的一件事就是使用抽象实现将CloudBlobContainer操作移至单独的服务。在这种情况下,您将能够模拟该服务,而完全不接触Azure类。
例如:
public interface IAzureServiceWrapper
{
CloudBlockBlob GetBlockBlobReference(CloudBlobContainer storageContainer, string fileName);
}
public class AzureServiceWrapper : IAzureServiceWrapper
{
public CloudBlockBlob GetBlockBlobReference(CloudBlobContainer storageContainer, string fileName)
{
storageContainer.GetBlockBlobReference(fileName).DeleteIfExists();
}
}
在这种情况下,模拟AzureServiceWrapper非常容易,并且此解决方案将解决单元测试中使用的Azure类的所有问题。您只需要在BlobStorageService中使用AzureServiceWrapper而不是CloudBlobContainer。