我试图模仿使用som泛型方法继承基类的Userservice。我无法模拟对RetrieveEntitiesTest的调用。
当我致电var validated = _userServiceMock.Object.ValidateUser(email, password);
时,会执行RetrieveEntitiesTest的实际执行......
这可能吗?您可以在下面查看我的代码:
public class BaseService
{
public virtual bool RetrieveEntitiesTest<T>(QueryExpression query)
{
return false;
}
}
public class UserService : BaseService
{
public bool ValidateUser(string username, string password)
{
// adding query parameters
var query = new QueryExpression();
var userCount = RetrieveEntitiesTest<User>(query);
return userCount > 0;
}
}
[TestFixture]
public class UserServiceTests
{
private Mock<UserService> _userServiceMock;
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
_userServiceMock = new Mock<UserService>();
}
[Test]
public void ValidateLogin_ValidEmailValidPassword_ValidatedAndReturnsTrue()
{
string email = "user@company.com";
string password = "password";
var query = .....
_userServiceMock.Setup(x => x.RetrieveEntitiesTest<User>(new QueryExpression())).Returns(true);
var validated = _userServiceMock.Object.ValidateUser(email, password);
Assert.IsTrue(validated);
}
}
答案 0 :(得分:3)
你没有正确设置你的模拟。使用It.IsAny(请参阅匹配参数部分)而不是新的QueryExpression:
_userServiceMock
.Setup(x => x.RetrieveEntitiesTest<User>(It.IsAny<QueryExpression>()))
.Returns(true);