C# 调用模拟对象的异步方法时出现NullReferenceException
我正在尝试使用MOQ对以下ViewModel的LoginExecute方法进行单元测试C# 调用模拟对象的异步方法时出现NullReferenceException,c#,unit-testing,asynchronous,mocking,mstest,C#,Unit Testing,Asynchronous,Mocking,Mstest,我正在尝试使用MOQ对以下ViewModel的LoginExecute方法进行单元测试 public class LoginViewModel : ViewModelBase, ILoginViewModel { INavigationService navigationService; IDialogService dialogService; IAdminService adminService; public RelayCommand LoginComma
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
}
我的测试是这样的
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
}
被称为NullReferenceException。正在引发NullReferenceException。如果在没有“wait”的情况下调用相同的方法,它将按预期工作。如果在正常的NavigationService实现中调用该方法(而不是模拟),它也可以正常工作。您能帮助我理解为什么异步方法调用会产生NullReferenceException吗?基于任务的异步模式的一部分是隐式假设,即该方法永远不会返回
null
这意味着对于所有异步方法,都需要模拟实际的返回值。我建议对“同步成功”案例使用
Task.FromResult
,“同步异常”案例使用TaskCompletionSource
,“异步成功/异常”案例使用async
lambda withTask.Delay
。我有类似的想法;我在异步任务上设置了回调,代码如下:
var navigationService = new Mock<INavigationService>()
.Setup(s => s.TestMethod())
.Callback(...);
今天被这件事抓住了,希望这能对有类似问题的人有所帮助。今天早上,这件事让我费了好几个小时的劲。