c# - NullReferenceException when calling async method of mocked object -


i'm trying unit test loginexecute method of following viewmodel using moq

public class loginviewmodel : viewmodelbase, iloginviewmodel {     inavigationservice navigationservice;     idialogservice dialogservice;     iadminservice adminservice;      public relaycommand logincommand { get; set; }      private string _productid;      public string productid     {         { return _productid; }         set         {             _productid = value;             raisepropertychanged("productid");         }     }      public loginviewmodel(inavigationservice navigationservice, idialogservice dialogservice, iadminservice adminservice)     {         this.navigationservice = navigationservice;         this.dialogservice = dialogservice;         this.adminservice = adminservice;         initializecommands();     }      private void initializecommands()     {         logincommand = new relaycommand(() => loginexecute());     }      public async task loginexecute()     {         await this.navigationservice.testmethod();         this.navigationservice.navigate(typeof(itherapistsviewmodel));     }      public void initialize(object parameter)     {     } } 

the inavigationservice looks this

    public interface inavigationservice {     frame frame { get; set; }     void navigate(type type);     void navigate(type type, object parameter);     task testmethod();     void goback(); } 

my test looks this

[testmethod()]     public async task logincommandtest()     {         var navigationservice = new mock<inavigationservice>();         var dialogservice = new mock<idialogservice>();         var adminservice = new mock<iadminservice>();         loginviewmodel loginvm = new loginviewmodel(navigationservice.object, dialogservice.object, adminservice.object);          await loginvm.loginexecute();          //asserts here     } 

the problem when line

await this.navigationservice.testmethod(); 

is called nullreferenceexception being thrown. if same method called without "await" works expected. works ok if method being called on normal navigationservice implementation (not mock of it). please me understand why async method call producing nullreferenceexception?

part of task-based asynchronous pattern implicit assumption method never returns null.

this means asynchronous methods, you'll need mock actual return value. recommend using task.fromresult "synchronous success" case, taskcompletionsource "synchronous exception" case, , async lambda task.delay "asynchronous success/exception" cases.


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -