在我的测试中,我将数据定义为List<IUser>
,其中包含一些记录。
我想设置moq方法Update
,此方法会收到用户id
和string
进行更新。
然后我获得IUser
并更新属性LastName
我试过了:
namespace Tests.UnitTests
{
[TestClass]
public class UsersTest
{
public IUsers MockUsersRepo;
readonly Mock<IUsers> _mockUserRepo = new Mock<IUsers>();
private List<IUser> _users = new List<IUser>();
[TestInitialize()]
public void MyTestInitialize()
{
_users = new List<IUser>
{
new User { Id = 1, Firsname = "A", Lastname = "AA", IsValid = true },
new User { Id = 1, Firsname = "B", Lastname = "BB", IsValid = true }
};
Mock<IAction> mockUserRepository = new Mock<IAction>();
_mockUserRepo.Setup(mr => mr.Update(It.IsAny<int>(), It.IsAny<string>()))
.Returns(???);
MockUsersRepo = _mockUserRepo.Object;
}
[TestMethod]
public void Update()
{
//Use the mock here
}
}
}
但我收到此错误:无法解析退货符号
你有身份证吗?
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<IUser> 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;
//....
}
}
答案 0 :(得分:61)
如果您只想验证调用此方法,则应使用Verifiable()方法。
_mockUserRepository.Setup(mr => mr.Update(It.IsAny<int>(), It.IsAny<string>()))
.Verifiable();
如果您还想对这些参数执行某些操作,请先使用Callback()。
_mockUserRepository.Setup(mr => mr.Update(It.IsAny<int>(), It.IsAny<string>()))
.Callback((int id, string lastName) => {
//do something
}).Verifiable();
<强>更新强>
如果你返回一个bool值,你应该如何模拟它。
_mockUserRepository.Setup(mr => mr.Update(It.IsAny<int>(), It.IsAny<string>()))
.Returns(true);
答案 1 :(得分:9)
Mock<IUsers> _mockUserRepository = new Mock<IUsers>();
_mockUserRepository.Setup(mr => mr.Update(It.IsAny<int>(), It.IsAny<string>()))
.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<int>(), It.IsAny<string>()), Times.Once());