Photo by Markus Winkler on Unsplash

Unit Testing is really important to guarantee that the code that we write is work. As a Software Engineer, sometimes dealing with testing can be little bit difficult to read, if we don’t do it in a clean and proper way.

SUT stands for System Under Test, is a system that is being tested. Usually, it can be a class or method, that we want to test the logic, so we can guarantee the code that we write is bug-free.

Why We Need System Under Test Helper Method?

So here is the example of making a test that is little bit hard to understand when we read it right away.

func test_load_shouldRespondSomething() {
let analytic: Inalytic = AnalayticSpy()
let storageClient: IUserDefaults = UserDefaultsSpy()
let serviceClient: IHTTPClient = HTTPClientSpy()
let storage: TextToSpeechPreferencesStorage = TextToSpeechPreferencesStorageImpl(client: storageClient)
let service: TextToSpeechPreferencesService = TextToSpeechPreferencesServiceImpl(client: serviceClient)
let repository: TextToSpeechPreferencesRepository = TextToSpeechPreferencesRepositoryImpl(
storage: storage,
service: service
)
let useCase: LoadLanguageIdPreferencesUseCase = LoadLanguageIdPreferencesUseCaseImpl(
repository: repository,
analytic: analytic
)
//
// other code
XCTAssertNotNil(useCase)
}

Extra effort for to read, right? Imagine we have more than one method in the Tests class. It will be a huge instance creation repetition. Bad code.

Using System Under Test

In the sample code, we can tell the SUT immediately by creating makeSUT helper method. By refactoring the instance that we want to test, we can see our SUT in an instant.

func test_load_shouldRespondSomething() {
let sut = makeSUT()
//
// other code
XCTAssertNotNil(sut)
}

And the `makeSUT()` helper method will be like below :

private func makeSUT() -> LoadLanguageIdPreferencesUseCase {
let analytic: Inalytic = AnalayticSpy()
let storageClient: IUserDefaults = UserDefaultsSpy()
let serviceClient: IHTTPClient = HTTPClientSpy()
let storage: TextToSpeechPreferencesStorage = TextToSpeechPreferencesStorageImpl(client: storageClient)
let service: TextToSpeechPreferencesService = TextToSpeechPreferencesServiceImpl(client: serviceClient)
let repository: TextToSpeechPreferencesRepository = TextToSpeechPreferencesRepositoryImpl(
storage: storage,
service: service
)
let useCase: LoadLanguageIdPreferencesUseCase = LoadLanguageIdPreferencesUseCaseImpl(
repository: repository,
analytic: analytic
)
return useCase
}

Conclusion

By using makeSUT helper method, we can simplify the instance creation that we are going to test and it can helps reading a lot better. So it is clear why it is better to use SUT helper method. Happy coding!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s