所以这就是我想要Mock的方法:
Function ReturnPasswordHistoryAsync(passwordChangeHistory As PasswordChangeHistory) As Task(Of IList(Of PasswordChangeHistory))
这是我的单元测试:
<TestMethod()> Public Async Function ValidateNewPassword_NewPasswordHasAlreadyBeenUsed_PasswordIsNotValid() As Task
'Arrange
Dim newPass = "newPass"
Dim oldPass = "oldPass"
Dim confirmPass = newPass
Dim passwordValid As PasswordValid
Dim ret As Task(Of IList(Of PasswordChangeHistory))
'Errors here with null object reference error
_mockChangePasswordRepo.Setup(Function(x) x.ReturnPasswordHistoryAsync(New PasswordChangeHistory())).Returns(ret)
'Act
passwordValid = Await _changePasswordManager.ValidateNewPassword(oldPass, newPass, confirmPass, Nothing)
'Assert
Assert.IsFalse(passwordValid.IsValid, "New password and old passord equal one another yet the test passed")
End Function
我认为由于返回而导致错误,但我不确定如何模拟返回类型。有谁知道如何模拟Task(Of IList(Of PasswordChangeHistory))
答案 0 :(得分:1)
If (results Is Nothing And results.Count > 0) Then
Return False
End If
事实证明,这实际上就是这个IF声明。结果是Nothing
,所以我认为IF会评估第二方,如果它返回false,则跳过第二部分。但它没有,所以伯爵抛出一个例外。
所以这是修复:
If results IsNot Nothing OrElse results.Count = 0 Then
Return False
End If
并且 - 评估双方
AndElse - 然后One Side确定IF是否有效
与Or和OrElse类似。
从C#到VB很奇怪,我想念我的语法糖
答案 1 :(得分:1)
看起来你正在使用Moq。对于模拟异步返回值,您可以使用ReturnsAsync
Dim ret As IList(Of PasswordChangeHistory) = New List(Of PasswordChangeHistory)
'Setup member to expect any value of PasswordChangeHistory and return a list after an async call
_mockChangePasswordRepo.Setup(Function(x) x.ReturnPasswordHistoryAsync(It.IsAny(Of PasswordChangeHistory))).ReturnsAsync(ret)
这将允许模拟流经Async / Await调用。