What is UnitTesting? What are UnitTests?

UnitTesting is testing a unit of functionality with other code.

UnitTests, in the context of c#, are simply classes with attributes. Usually they are called test fixtures which contain test cases. Test cases are just methods with a Test attribute on them. UnitTests are mostly concerned with testing interaction between classes or logical outcomes. Interaction tests test for the correct interaction between classes, usually with Stub or Mock objects. An interaction test might test for a web service call with a specific message. Logical tests test that the given business logic is working was expected. For example making sure a filter on insurance applications actually filters out applications. Both of these test types will use Assertions to make sure what was expected to happen did happen. An Assertion is really just a logical check that throws an exception if it’s false. If a test has Assert.AreEqual(expected, actual) and expected does not equal actual it will throw an exception, with details, to fail the test.
Here is a super simple test to make sure the test framework is working correctly.

using MbUnit.Framework;
namespace IntroToUnitTests.Tests

<span class="kwrd">public</span> <span class="kwrd">class</span> TestFixture
    <span class="kwrd">public</span> <span class="kwrd">void</span> Is_The_Test_Framework_Working()
        Assert.IsTrue(<span class="kwrd">true</span>);


Why would I want to write tests? What are the advantages?

  • Unit tests allow code to be changed and refactored without worrying about breaking the expected functionality.
  • Unit tests promote better design and cleaner, simpler code.
  • Unit tests help document the intent of code.
  • Unit tests help make sure bugs do not come back to life.
  • Unit tests help reduce time in the debugger.

Why wouldn't I want to write tests? What are the challenges?

Unit testing the UI is typically a very challenging. WebForms usually make unit testing really hard or impossible. This is partly because recreating the ASP.Net life cycle is not possible. And partly because it's really easy to mix business concerns with UI concerns.

Unit testing databases is challenging on two fronts. First having a way to create a clean DB for testing. Secondly, keeping the test time reasonable.

Legacy Code, which is often considered code without tests, is challenging because before you change legacy code it needs tests, but often you need to change the code to be more testable.

Who writes and maintains these tests?

Developers are responsible for writing, maintaining, and running unit tests. The build/release process should also be responsible for running and failing if any of the unit tests fail.

I hope this provides basic high level overview of unit testing, and idea of what value they might add and what challenges they might present. More detailed posts will be coming soon.