Tuesday, October 11, 2011

Constructor vs. ClassInitialize

I recently ran across some code in a test class where I saw that the class was initialized in a constructor rather than in a method with the ClassInitialize method, and it made me wonder - what's the difference?

The goal is that we have a test class with several test methods, and we have some initialization code that is common to all of the test methods.  We want the initialization code to run only once for the entire set of tests, not once per test.

One way to do this is to put the initialization code in the constructor, like this:

        public MyTestClass()
        {
            var x = 5;
            x.Should().Be(4);  // Fluent Assertions
        }

Another way is to create a static method with the ClassInitialize attribute, like this:

        [ClassInitialize]
        public static void Init(TestContext testContext)
        {
            var x = 5;
            x.Should().Be(4);  // Fluent Assertions
        }

So what's the difference?