开发者

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.AreE开发者_运维技巧qual<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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜