我正在尝试为“MethodToTest”编写测试,如下所示
Public Class UserService()
{
private IRepository<User> _userRepo;
public UserService(IRepository<User> userRepo = null)
{
_userRepo = userRepo ?? new UserRepository();
}
public List<string> MethodToTest(string userName)
{
var user = _userRepo.Find(u => u.Email == userName).First<User>();
//Other stuff that eventually returns a List<string>
}
}
我的测试中有以下内容
[Test]
public void GetItemsByUserName_UserName_ListOfItems()
{
var userName = "AnyString";
var fakeUserRepo = new Mock<IRepository<User>>();
var fakeUserList = new List<User>()
{
new User()
{
Email = userName,
Roles = new List<Role>()
{
new Role()
{
Name="Role1"
},
new Role()
{
Name="Role2"
}
}
}
};
var fakeUserListQueryable = fakeUserList.AsQueryable<User>();
var query = new Func<User, bool>(u => u.Email == userName);
fakeUserRepo.Setup(u => u.Find(query)).Returns(fakeUserListQueryable);
var userService = new UserService(fakeUserRepo.Object);
var menu = userService.GetMenuByUserName(userName);
//Assert Something
}
问题是我无法让 _userRepo 的 find 方法返回我的虚假用户列表。
运行测试时,执行时出现“序列不包含元素”
_userRepo.Find(u => u.Email == userName).First<User>();
在 MethodToTest 中。我究竟做错了什么?