[英]Mock an update method returning a void with Moq
在我的測試中,我將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
}
}
}
但我得到這個錯誤: 無法解決返回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<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;
//....
}
}
如果您只想驗證調用此方法,則應使用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);
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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.