Intuitive and clean mocking for automated tests — with example in .NET Core

Magnus Stuhr
Compendium
Published in
6 min readAug 25, 2019

--

Robert C. Martin argues in his book “Clean Code” (2009, page 133) that writing clean test-code is perhaps even more important than writing clean production-code, “because tests preserve and enhance the flexibility, maintainability, and reusability of the production code”. I very much agree with him. Even when assuming that all the business logic in the production code are covered by automated tests, the code will be hard to extend or maintain if the test-code is poorly written.

Test-code with code-duplication, lack of readability, non-intuitive naming conventions, or lack of formatting, to name a few, will lead to fear of maintaining or extending the production code, difficulties adapting tests to new requirements, and may in worst case even lead to the discarding of existing tests and writing new ones. In other words, if the test-code is not written cleanly, one can argue the entire code-base is in a rotten state.

Mocking is the practice of simulating and verifying behavior of objects, mostly as a part of automated testing. It enables a loose coupling between dependent components by being in full control of its implementation-specific details,
instead of relying on any real-world implementation, which may change or be replaced over time. Also, mocking requires minimal resources, thus…

--

--