Here are the things that are on my mind that make tests more consistent, more readable, more reliable
-
Start with a template of
// Resharper code template [NUnit.Framework.Test] public void When_$TESTNAME$() { // Arrange $END$ // Act // Assert }
- DAMP (Descriptive And Meaningful Phrases)
- The
Act
line will generally be a single statement,Assert
should also be very close to 1 statement,Arrange
is how to use your class, I aim to never need to hide that away in a sharedSetup
method - This template helps the readability of a unit test a shocking amount, a test will generally fail in the setup, the actions, or the assertions, so help out whoever might need to debug your test (future you especially) by instantly narrowing down where they need to start reading
- As well as helps keeps unit tests single-responsibility, since its obvious if you need to arrange something else after acting
-
I prefer test names starting with
When
, it helps me think about how this will be being used- I don't mind the idea of having nested classes (similar to RSpec nesting
describe
blocks, or whatever JS test framework I've seen doing that), but it seems overkill for me most of the time
- I don't mind the idea of having nested classes (similar to RSpec nesting
-
Aim for a single
Assert
or similar in each test, or at least very closely related asserts -
Read about all the features in your testing framework, some can be nearly unknown yet massively helpful (
TestCaseSource
in NUnit for example) -
Consider alternative assertion frameworks (for C# I much prefer FluentAssertions)
-
Using IoC in UnitTests is a massive code smell to me
-
Limit usage of Magical Mocking Frameworks in unit tests where possible, it can allow you to write noop tests accidentally, and understand the system less (which can be a benefit in some systems)
- With mocking the unit test is a testing an very small unit of code. Without mocking the unit test is usage documentation as well
- Any mid-level developer should be able to effectively write unit tests without any framework involved
-
Explore unit test guidelines and frameworks for various languages, there is always something to learn from them
TODO gather more thoughts on this