I use .Net Core 2.0
for my project, and Moq v4.7.145
- my fake framework.
I have this protected virtual method that usually uploads bytes to the cloud service. To be able to unit test, I wanted to make fun of this method, which works great for all other scenarios.
The problem occurred when I want to return this method null
. This is to simulate a service down or actually return null
. I checked a few questions about SO, but no one is working.
I mocked my picture provider as follows. mockProvider
- this is the layout of the cloud service, and LoggerMock
- the layout is good ... the registrar.
PictureProvider = new Mock<CloudinaryPictureProvider>(mockProvider.Object, LoggerMock.Object)
{
CallBase = true
};
I set my mocked method as follows:
PictureProvider.Protected()
.Setup<Task<ReturnObject>>("UploadAsync", ItExpr.IsAny<ImageUploadParams>())
.Returns(null as Task<ReturnObject>);
, .
, , :
protected virtual async Task<ReturnObject> UploadAsync(ImageUploadParams uploadParams)
{
var result = await _cloudService.UploadAsync(uploadParams);
return result == null ? null : new ReturnObject
{
};
}
, , :
public async Task<ReturnObject> UploadImageAsync(byte[] imageBytes, string uploadFolder)
{
if (imageBytes == null)
{
}
var imageStream = new MemoryStream(imageBytes);
var uploadResult = await UploadAsync(new ImageUploadParams
{
File = new FileDescription(Guid.NewGuid().ToString(), imageStream),
EagerAsync = true,
Folder = uploadFolder
});
if (uploadResult?.Error == null)
{
return uploadResult;
}
{
}
}
, protected (Mocked) public UploadImageAsync
, NullReferenceException
:
Message: Test method {MethodName} threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.
, - , , . / -, , !