模拟测试依赖注入对象引用
问题描述:
首次使用模拟创建单元测试。我有问题,因为我在对象引用上出错。模拟测试依赖注入对象引用
Mock<IAccount> mock = new Mock<IAccount>();
var testController = new AccountController(mock.Object);
IActionResult result = testController.Withdraw(1,100,"sample");
Assert.IsInstanceOfType(result, typeof(RedirectToActionResult));
下我AccountController
类存款方法
var _account = _Iaccount.GetAccountById(id);
if (_account.Password != password)
{
ModelState.AddModelError("Password", "Invalid Password!");
}
具有上_Iaccount
错误,因为它是在构造。
谢谢!
答
您必须设置一个模拟对象
var returnAccount = new Account { Name = "Ali" };
mock.Setup(s => s.GetAccountById(It.IsAny<Guid>())).Returns(returnAccount);
GetAccountById
将返回returnAccount
可否请你添加更多的信息?例如你的控制器的代码。此外,请附上整个错误消息。谢谢 – Christos
如何注册我的存储库接口?看来我需要先注册它? –