简体   繁体   中英

Mock testing dependency injection object reference

First time to create unit testing using mock. I'm having problem as I'm having error on object reference.

Mock<IAccount> mock = new Mock<IAccount>();
var testController = new AccountController(mock.Object);

IActionResult result = testController.Withdraw(1,100,"sample");
Assert.IsInstanceOfType(result, typeof(RedirectToActionResult));

under my AccountController class on deposit method

var _account = _Iaccount.GetAccountById(id);
if (_account.Password != password)
{
    ModelState.AddModelError("Password", "Invalid Password!");
}

having error on _Iaccount as it was on the constructor.

thanks!

You must setup a mock object

var returnAccount = new Account { Name = "Ali" };
mock.Setup(s => s.GetAccountById(It.IsAny<Guid>())).Returns(returnAccount);

GetAccountById will return returnAccount

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM