我正在尝试使用MOQ对以下ViewModel的LoginExecute方法进行单元测试。
public class LoginViewModel : ViewModelBase, ILoginViewModel
{
INavigationService navigationService;
IDialogService dialogService;
IAdminService adminService;
public RelayCommand LoginCommand { get; set; }
private string _productID;
public string ProductID
{
get { 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)
{
}
}
INavigationService的样子如下所示
public interface INavigationService
{
Frame Frame { get; set; }
void Navigate(Type type);
void Navigate(Type type, object parameter);
Task TestMethod();
void GoBack();
}
我的测试看起来像这样
[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 will be here
}
问题在于当行
await this.navigationService.TestMethod();
被称为 NullReferenceException 的异常被抛出。如果不使用 "await" 调用同样的方法,则会按预期工作。如果在正常的 NavigationService 实现上调用该方法(而不是其模拟),它也可以正常工作。请帮助我理解为什么异步方法调用会产生 NullReferenceException?