模拟一个使用Moq返回void的更新方法
在我的测试中,我将List
定义为数据,其中包含一些记录。
我想设置一个moq的方法Update
,这个方法接收用户id
和要更新的string
。
然后我获取IUser
并更新属性LastName
我试过这个:
namespace Tests.UnitTests { [TestClass] public class UsersTest { public IUsers MockUsersRepo; readonly Mock _mockUserRepo = new Mock(); private List _users = new List(); [TestInitialize()] public void MyTestInitialize() { _users = new List { new User { Id = 1, Firsname = "A", Lastname = "AA", IsValid = true }, new User { Id = 1, Firsname = "B", Lastname = "BB", IsValid = true } }; Mock mockUserRepository = new Mock(); _mockUserRepo.Setup(mr => mr.Update(It.IsAny(), It.IsAny())) .Returns(???); MockUsersRepo = _mockUserRepo.Object; } [TestMethod] public void Update() { //Use the mock here } } }
但我得到这个错误: 无法解决返回symbole
你有身份证吗?
class User : IUser { public int Id { get; set; } public string Firsname { get; set; } public string Lastname { get; set; } public bool IsValid { get; set; } } interface IUser { int Id { get; set; } string Firsname { get; set; } string Lastname { get; set; } bool IsValid { get; set; } } interface IAction { List GetList(bool isActive); void Update(int id, string lastname) } class Action : IAction { public IUser GetById(int id) { //.... } public void Update(int id, string lastname) { var userToUpdate = GetById(id); userToUpdate.LastName = lastname; //.... } }
如果您只想validation调用此方法,则应使用Verifiable()方法。
_mockUserRepository.Setup(mr => mr.Update(It.IsAny(), It.IsAny())) .Verifiable();
如果您还想对这些参数执行某些操作,请先使用Callback()。
_mockUserRepository.Setup(mr => mr.Update(It.IsAny(), It.IsAny())) .Callback((int id, string lastName) => { //do something }).Verifiable();
更新
如果你返回一个bool值,你应该如何模拟它。
_mockUserRepository.Setup(mr => mr.Update(It.IsAny(), It.IsAny())) .Returns(true);
Mock _mockUserRepository = new Mock (); _mockUserRepository.Setup(mr => mr.Update(It.IsAny(), It.IsAny())) .Callback((int id, string name) => { //Your callback method here }); //check to see how many times the method was called _mockUserRepository.Verify(mr => mr.Update(It.IsAny(), It.IsAny()), Times.Once());