Skip to content

SUT Factory

SUT factory may be a fancy name to what is basically a utility method, used to create an instance of the system under test. The main point of a SUT Factory is to reduce code duplication and improve maintainability of your unit tests suite.

I’ll show you a quick example of how can you implement this type of utility method.

Imagine a test like this one:

[TestMethod]
public void TestUsingConstructor()
{
    //Arrange
    MySUT sut = new MySUT();

    //Act
    //...Exercise  the sut

    //Assert
    //...Verifying the results
}

You can see that in this test we’re just creating our system under test, exercising and checking the outcome, usual stuff. Imagine if a new requirement was requested and we end up with a constructor like this:

public MySUT(IMyDependency dependeny)
//...
//Rest of the implementation
//...

Now all of MySUT’s tests that use the default constructors will break. Because they don’t have this dependency, we would’ve to update all tests to account for this new requirement, just to compile the code.

Instead of doing this, we can create a factory method for the class, then we’ll have a single place to update the creation logic:

private MySUT CreateMySUT()
{
    IMyDependency myDependency = new MyDependencyFake();

    return new MySUT(myDependency);
}
[TestMethod]
public void TestUsingFactoryMethod()
{
    //Arrange
    MySUT sut = CreateMySUT();

    //Act
    //...Exercise  the sut

    //Assert
    //...Verifying the results
}

Every time that MySUT’s constructor needs to be changed, we update the CreateMySUT method. This helps to remove duplication and improve maintainability of your test.

References for Further Reading

Published inUnit Test

2 Comments

  1. […] One of the techniques to avoid code duplication in the tests is to create a SUT factory. A SUT factory is an auxiliary method or a class that is in charge of creating the system under test instance. I wrote a post talking about the SUT factory more in-depth, you can check it here. […]

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: