在 AutoFixture 中为测试类创建匿名类型的目的是什么?
我最近开始使用 AutoFixture 库(http://autofixture.codeplex.com/)进行单元测试,我非常喜欢它。
我从 AutoFixture CodePlex 网站获取了此代码示例。我的问题是关于第 8 行。
1. [TestMethod]
2. public void IntroductoryTest()
3. {
4. // Fixture setup
5. Fixture fixture = new Fixture();
6.
7. int expectedNumber = fixture.CreateAnonymous<int>();
8. MyClass sut = fixture.CreateAnonymous<MyClass>();
9.
10. // Exercise system
11. int result = sut.Echo(expectedNumber);
12.
13. // Verify outcome
14. Assert.AreEqual<int>(expectedNumber, result, "Echo");
15. // Teardown
16. }
我不明白为什么我们需要创建被测试类的匿名对象。
MyClass sut = fixture.CreateAnonymous<MyClass>();
在我看来,该类应该是真实的对象。举个例子..
var sut = new MyClass();
我的问题是,创建一个匿名对象来测试的真正好处是什么?
I recently started using AutoFixture library (http://autofixture.codeplex.com/) for Unit Testing and I quite like it.
I got this code sample from the AutoFixture CodePlex website. My question is in regards to line number 8.
1. [TestMethod]
2. public void IntroductoryTest()
3. {
4. // Fixture setup
5. Fixture fixture = new Fixture();
6.
7. int expectedNumber = fixture.CreateAnonymous<int>();
8. MyClass sut = fixture.CreateAnonymous<MyClass>();
9.
10. // Exercise system
11. int result = sut.Echo(expectedNumber);
12.
13. // Verify outcome
14. Assert.AreEqual<int>(expectedNumber, result, "Echo");
15. // Teardown
16. }
I can't understand, why we need to create an anonymous object of the class under test.
MyClass sut = fixture.CreateAnonymous<MyClass>();
The class should be the real object IMO. For an example..
var sut = new MyClass();
My question is, what is the real benefit of creating an anonymous object to test against?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在微不足道的情况下,你是正确的 - 没有实质性差异。
然而,SUT API 封装有其用途——作为您的系统正在测试及其夹具对象比具有默认构造函数的对象更有趣(它真的没有依赖项吗?),例如:
MyClass
需要将内容输入到其构造函数中MyClass
的构建还有您想要的任何其他内容 应用策略然后拥有Sut Factory 参与开始发挥作用,让无关的代码消失并允许您应用横切关注点到这个过程。
编辑:出于某种原因 @Brad Wilson 看到了适合转发这篇文章,这有点突出
In the trivial case you are correct - there is no material difference.
However, SUT API Encapsulation has its uses -- as your System Under Test and its Fixture Objects get more interesting than something with a default ctor (does it really have no dependencies?), e.g.:
MyClass
requires stuff to be fed into it's constructorsMyClass
has anything else you want to apply a policy toThen the power of having a Sut Factory involved starts coming into play, letting extraneous code fall away and allowing you to apply cross-cutting concerns to the process.
EDIT: For some reason @Brad Wilson saw fit to repost this article which is kinda salient