Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The purpose of creating anonymous types in AutoFixture for class under tests?

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?

like image 861
Spock Avatar asked May 31 '11 12:05

Spock


People also ask

What is an anonymous type in C#?

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.

What is AutoFixture C#?

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.


1 Answers

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 constructors
  • `MyClass has read/write properties that you don't want default values to apply to (programming by coincidence)
  • the bulding of MyClass 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

like image 119
Ruben Bartelink Avatar answered Sep 28 '22 08:09

Ruben Bartelink