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

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

Comments

Projects
None yet
3 participants

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.

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

Owner

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 Jul 14, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment