gpt4 book ai didi

c# - 英孚。模拟 ICollection

转载 作者:太空宇宙 更新时间:2023-11-03 10:49:50 25 4
gpt4 key购买 nike

我有类模型角色:

public partial class Role
{
public Role()
{
this.Users = new HashSet<User>();
}

public int Id { get; set; }
public string RoleName { get; set; }

public virtual ICollection<User> Users { get; set; }
}

在进行单元测试时我需要模拟它。所以我有代码:

public class RoleControllerTest
{
private IUnitOfWork fakeRepo;
[TestInitialize]
public void Initialize()
{
Mock<IUnitOfWork> mock = new Mock<IUnitOfWork>();
mock.Setup(m => m.roleRepository.Get(null)).Returns(new[]{
new Role{Id=1, RoleName="Admin",MissingArgument},
new Role{Id=2,RoleName="User",MissingArgument}
});
}
}

我不知道如何模拟

public virtual ICollection<User> Users { get; set; }

试过 null 但此 alsa 返回错误。你能建议我应该传递什么变量和什么类型来代替 MissingArgument 吗?

最佳答案

我假设 Moq - Users 只是您要为其生成假数据的 Role 类的一个属性,所以您可以继续使用对象初始化器语法在模拟的 Get 实现的 Returns 中初始化它,如下所示:

    Mock<IUnitOfWork> mock = new Mock<IUnitOfWork>();
mock.Setup(m => m.roleRepository.Get(It.IsAny<int>()))
.Returns(new[]{
new Role
{
Id=1,
RoleName="Admin",
Users = new List<User>
{
new User
{
// Set SomeUserProperties Here
},
// Add another User here if needed
}},
new Role
{
Id=2,
RoleName="User"
// Add users here
}
}
);

如果您发现自己需要在多个单元测试中返回相同的假数据,您可以创建一组常见的固定 static readonly 对象或使用 object mother factory对于各种用户角色,这将使您的代码变干。

关于c# - 英孚。模拟 ICollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21852278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com