[英]Autofixture c# create a list of objects with one custom object
I am using [AutoFixture][1] in my unit test, to simplify my test setup.我在我的单元测试中使用 [AutoFixture][1] 来简化我的测试设置。 Sometimes I have the use case that I need a list with one specific object.
有时我有一个用例,我需要一个包含一个特定对象的列表。
var inputValues = AutoFixture.Build<TestObject>().CreateMany().ToList();
inputValues[0] = new TestObject { name = "best guy"}
Currently I solve this my issue with the code snipping below.目前,我通过下面的代码剪辑解决了这个问题。 I am sure there is a better solution.
我相信有更好的解决方案。
I find this post [Create a list with specific values with Autofixture C#][2] but I am really happy this such solution.我发现这篇文章 [使用 Autofixture C# 创建具有特定值的列表][2] 但我真的很高兴这个解决方案。
I am also aware of something like this:我也知道这样的事情:
var inputValues = AutoFixture.Build<TestObject>().With(c => c.Name = "test" ).CreateMany().ToList();
But this will set all list entries with the same value.但这会将所有列表条目设置为相同的值。 [1]: https://github.com/AutoFixture/AutoFixture [2]: https://stackoverflow.com/a/66653510/9533580
[1]: https : //github.com/AutoFixture/AutoFixture [2]: https : //stackoverflow.com/a/66653510/9533580
This question has been answered a couple times already on SO.这个问题已经在 SO 上回答了几次。 You can see the answers here and here .
你可以在这里和这里看到答案。
The best option is to inject the custom object/value into an existing collection.最好的选择是将自定义对象/值注入现有集合。 Similar to the first example you provided.
类似于您提供的第一个示例。
If you really wanted to, you could create a specimen builder that counts the number of times it returned a value and stop after the first one, but really this is not worth the effort.如果你真的想,你可以创建一个样本生成器,它计算它返回一个值的次数并在第一个之后停止,但实际上这不值得付出努力。 Also your test would be worse because you would make it less obvious for a reader how exactly that unique item is different from the other.
此外,您的测试会更糟,因为您会让读者不那么明显地看到该独特项目与其他项目的不同之处。
Perhaps if you would provide a more specific example, it would be easier to offer you some advice.也许如果你能提供一个更具体的例子,给你一些建议会更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.