设置实体的 ID 属性仅用于单元测试目的,该实体具有私有/初始化设置器
为了便于单元测试,我尝试创建一个 Helper 类,它基本上允许我获取设置了默认值的实体。
var user = EntityFactory.NewUser(emailAddress: "[email protected]");
在命名参数的帮助下,如果我愿意,我可以覆盖一些值。
问题是我需要创建 2 个具有不同 ID 的用户,但如下所示的 Id
属性有一个 init
setter,我不想将其设为公共setter,因为它在我的应用程序中没有任何意义,因为 ID 是由数据库生成的。另外,出于同样的原因,我也不想更改构造函数。
那么我该如何解决这个问题呢?让它成为公共 setter 可以吗?或者我是否需要在排列阶段首先将实体保存在数据库中(如果实体具有也需要首先保存的依赖项怎么办)?或者有没有更好的方法来解决此类问题?
我不想在这里使用任何模拟库,因为我想对真实对象进行测试。
public static class EntityFactory
{
public static User NewUser(long id = 0, string firstName = "firstname", string lastName = "lastname",
string emailAddress = "[email protected]", DateTime dateOfBirth = default, long stateId = 0)
{
if (dateOfBirth == default)
{
dateOfBirth = new DateTime(2000, 1, 1);
}
var user = new User(firstName, lastName, emailAddress, dateOfBirth, stateId);
user.Id = id; // Init Property, can't set here.
return user;
}
}
For ease in unit tests, I am trying to create a Helper class which basically allows me to get Entities with default values set.
var user = EntityFactory.NewUser(emailAddress: "[email protected]");
With the help of named arguments I can override some values if I want.
The problem is I need to create 2 users with different IDs but the Id
property as you can see below has an init
setter and I don't want to make it a public setter as it won't make any sense in my application as IDs are being generated by the Database. Also I don't want to change constructor as well for the same reason.
So how would I approach this problem? Is it OK to make it a public setter? Or do I need to save the entities in the DB first in the Arrange phase (What if the entities had dependencies which also need to be saved first)? Or are there any better approaches to solve these kinds of problems?
I don't want to use any mocking library here as I want to do the testing on real objects.
public static class EntityFactory
{
public static User NewUser(long id = 0, string firstName = "firstname", string lastName = "lastname",
string emailAddress = "[email protected]", DateTime dateOfBirth = default, long stateId = 0)
{
if (dateOfBirth == default)
{
dateOfBirth = new DateTime(2000, 1, 1);
}
var user = new User(firstName, lastName, emailAddress, dateOfBirth, stateId);
user.Id = id; // Init Property, can't set here.
return user;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1年后,我觉得这不是一个好的测试方式。任何类型的测试,无论是单元/集成还是任何其他。应该始终测试行为而不是实现。
在这种情况下,我的目标是实施。由于我正在开发一个 Web 应用程序,因此我应该编写测试来使用 HTTP 调用来调用我的应用程序,因为这是我的应用程序公开的行为。
After 1 year later, I think this is not a good way of testing. Any kind of test whether unit/integration or any other. Should always test the behavior and not the implementation.
In this case I was targeting the implementation. Since I was developing a web app I should have written tests which would invoke my application using HTTP calls because that is the behavior exposed by me app.