Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Verifiable throw NullReferenceException for async Task methods #101

Closed
CriggerMarg opened this issue Mar 4, 2014 · 2 comments
Closed

Verifiable throw NullReferenceException for async Task methods #101

CriggerMarg opened this issue Mar 4, 2014 · 2 comments

Comments

@CriggerMarg
Copy link

Have interface

 public interface IDataStoreService
    {
        Task<T> GetDataAsync<T>(string key);
        Task SaveDataAsync<T>(string key, T item, bool storeAlways = false);
    }

In test create mock object

 var mockDataService = new Mock<IDataStoreService>();
            mockDataService.Setup(
                service => service.SaveDataAsync(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<bool>())).Verifiable();

Act it with this code

 var settingsService = new MyStorageService(mockDataService.Object);
  var rez = await settingsService.Set("setting", "ok");

Moq throws NullReferenceException on SaveDataAsync call in MyStorageService.

If I change interface method to

   Task<bool> SaveDataAsync<T>(string key, T item, bool storeAlways = false);

and change setup to

   mockDataService.Setup(
                service => service.SaveDataAsync(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<bool>())).ReturnsAsync(true);

all works fine.

@jamesbascle
Copy link

Also just ran into this problem...Seems you can't properly mock methods that simply return a task?!

@kzu
Copy link
Contributor

kzu commented Jul 14, 2016

You're not returning a task, therefore, a null is being returned.

If your method signature returns a task, you need to return one ;)

var mockDataService = new Mock<IDataStoreService>();
mockDataService.Setup(
            service => service.SaveDataAsync(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<bool>()))
       .Returns(Task.FromResult(true)).Verifiable();

Note that a Task is a Task, so you can return that just fine. No need to change the method signature.

@kzu kzu closed this as completed Jul 14, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants