好吧,正如我在评论中所说,我不清楚您要测试什么代码。我在这里看到两个选项。1)Users
该类实现IUsers
接口,您的意图是测试GetById(int)
方法的实现。在这种情况下,您不需要模拟 'Users#GetById(id)' 方法,您只需要调用它并检查结果。代码应类似于:
interface IUser
{
int Id { get; }
}
class User : IUser
{
public int Id { get;set; }
}
interface IUsers
{
IUser GetById(int id);
}
class Users : IUser
{
public IUser GetById(int id)
{
// TODO: make call db call
// TODO: parse the result
// TODO: and return new User instance with all the data from db
return new User{ Id = id };
}
}
[TestMethod]
public void MyMoq()
{
// TODO: prepare/mock database. That's whole another story.
var users = new Users();
// act
var user = users.GetById(10);
// assert
Assert.AreEqual(10, user.Id);
}
2)您的Users#GetById(int)
方法应该调用IUsers#GetById(int)
并返回结果。在这种情况下,您需要创建模拟IUsers
(如您在问题中所示)并将其传递给Users
. 代码应该是(抱歉可能重复):
interface IUser
{
int Id { get; }
}
class User : IUser
{
public int Id { get;set; }
}
interface IUsers
{
IUser GetById(int id);
}
class Users : IUser
{
private readonly IUser _users;
public Users(IUser users)
{
_users = users;
}
public IUser GetById(int id)
{
// next line of code is to be tested in unit test
return _users.GetById(id);
}
}
[TestMethod]
public void MyMoq()
{
var usersMock = new Mock<IUsers>();
usersMock.Setup(x => x.GetById(10)).Returns(new User());
var users = new Users(usersMock.Object);
// act
var user = users.GetById(10);
// assert
Assert.AreEqual(10, user.Id);
}
ps 查看起订量教程和单元测试艺术一书(第 47 页)可能很有用Part 2 - Core techniques
- 存根、模拟等。