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?
Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer.
AutoFixture is designed to make Test-Driven Development more productive and unit tests more refactoring-safe. It does so by removing the need for hand-coding anonymous variables as part of a test's Fixture Setup phase. Among other features, it offers a generic implementation of the Test Data Builder pattern.
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 to
Then 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With