Mocked method with moq to return null throw NullReferenceException

I use .Net Core 2.0for 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 so it will only overwrite the method I want to be mocked.
    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
    {
        // Setting values from the result object
    };
}

, , :

public async Task<ReturnObject> UploadImageAsync(byte[] imageBytes, string uploadFolder)
{
    if (imageBytes == null)
    {
        // Exception thrown
    }

    var imageStream = new MemoryStream(imageBytes);

    // It throws the NullReferenceException here.
    var uploadResult = await UploadAsync(new ImageUploadParams
    {
        File = new FileDescription(Guid.NewGuid().ToString(), imageStream),
        EagerAsync = true,
        Folder = uploadFolder
    });

    if (uploadResult?.Error == null)
    {
        // This is basically the if statement I wanted to test.
        return uploadResult;
    }

    {
        // Exception thrown
    }
}

, protected (Mocked) public UploadImageAsync, NullReferenceException:

Message: Test method {MethodName} threw exception:   
System.NullReferenceException: Object reference not set to an instance of an object.

, - , , . / -, , !

+4
1

ReturnsAsync((ReturnObject)null) Returns(null as Task<ReturnObject>). Returns(Task.FromResult((ReturnObject)null))

, , , Returns . ReturnsAsync Task.FromResult, .

public static IReturnsResult<TMock> ReturnsAsync<TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<TResult> valueFunction) where TMock : class
{
    return mock.Returns(() => Task.FromResult(valueFunction()));
}

public static IReturnsResult<TMock> ReturnsAsync<TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, TResult value) where TMock : class
{
    return mock.ReturnsAsync(() => value);
}
+4

Source: https://habr.com/ru/post/1691015/


All Articles