Reusable Self-Explanatory Mockings for Fast Quality Unit Test Writing. — .NET Code Samples included.

Džiugas Garla
C# Programming
Published in
3 min readMar 27, 2024

What is the purpose of mock objects?

A Mock Object acts as a substitute for an actual object, imitating its behavior under controlled circumstances. In software development, mocks replicate the behavior of real objects and assist in testing various components.

Much like how creators of protective vests utilize test dummies to replicate human responses of impact. Programmers create mock objects. They use them to assess the behaviour of specific objects in a system.

Developers can use mock objects. They let you create test scenarios without relying on things like databases. Mock objects simulate their behaviour. This is without the overhead of using a live database for each test.

Source: https://stackoverflow.com/a/3622466/12959213

Mocking setups

Mocking setups enhance code readability. They follow the KISS principle to keep it simple and DRY principle to avoid repetition. This is done with extension methods. They let you “add” methods to existing `Mock<…>` types. More information about .NET extension methods can be found here.

Here are the key advantages of why I like to use mocking setups:

Clear Naming: Each mocking setup is named to clearly explain its purpose. A lack of self-explaining mockings will lead to confusion and extra effort to decipher mocking purpose.

Reusability: Write once, and use multiple times. Ignoring reusability leads to duplicating code. This leads to more maintenance and potential inconsistencies.

Intuitive Design: It just intuitively looks right and nice, resulting in code that looks less cluttered.

Yup, this is a good time-saving and self-explaining deal.

How it works:

It is pretty simple if you understand extension methods. You simply need to create an extension method for Mock<...>.

For instance, you have the Mock<IFileIOManager> mock:

Mock<IFileIOManager>

Now, if you need to set up a mock for its ReadStringAsync() method:

IFileIOManager contains ReadStringAsync() method which one I want to mock.

The creation of the mock setup extension should resemble this:

Setup_ReadString_ReturnString(mockRepository, str) extension mocks ReadString() method to always return predefined string.

Then, in your tests, you can call this extension as follows:

The extension returns itself. Every setup can connect by a dot, like a chiuku chiuku train:

Easy to connect
Chiuku chiuku train. Image by author generated on Fotor.

Thank you for taking the time to read this article.

I encourage you to share your insights to aid in enhancing future articles!

--

--

Džiugas Garla
C# Programming

Turning endless motyvation into code since forever.