About a year ago I was experimenting with local functions and reflection, to improve my unit tests and the way to write BDD specs. I had been using Machine.Specifications and Machine.Fakes for years. MSpec has served me well, but the lack of async support made me look for alternatives.

The experiment with local functions in tests led to the release of LoFuUnit:

Testing with Local Functions 🐯

in .NET / C# ⚙️

with your favorite Unit Testing Framework ✔️

Recently I published version 1.1.1 of LoFuUnit, so I thought it would be a good time to introduce the framework to you in the form of a blog post.

Tests

Let’s try LoFuUnit and see how tests are written. I’ll use the same challenge from a previous blog post about BDD frameworks for .NET / C#:

The subject

The stack, a last-in-first-out (LIFO) collection:

The tests will assert the behavior of:

  • Empty vs nonempty stack
  • Peek() and Pop() methods
  • InvalidOperationException

Stack

Tests with LoFuUnit.NUnit:

  • LoFuUnit.NUnit provides the [LoFu] attribute, apply it to your test methods
  • Write the test steps in local functions, they are implicitly invoked by the [LoFu] attribute
  • Think about the naming of test methods and test functions, it will determine the test output

Test output:

Unit Test Sessions

Unit Test Sessions

Auto Mocks

Mocking is nice, automocking is even better

Auto-mocking is part of LoFuUnit. Let’s see how auto-mocked tests are written. I’ll use the same challenge from a previous blog post about Automocked base class for NUnit tests:

The subject:

Auto-mocked tests with LoFuUnit.AutoNSubstitute and LoFuUnit.NUnit:

  • LoFuUnit.AutoNSubstitute provides the base class LoFuTest<TSubject>, inherit your test fixtures from it
  • The Use<TDependency>() methods gives you the ability to setup the mocks
  • The The<TDependency>() method lets you access the mocks and verify expectations

Test output:

Unit Test Sessions

Installation

LoFuUnit is distributed as 7 packages via NuGet. The code examples in this blog post used two of them.

LoFuUnit.NUnit:

LoFuUnit.AutoNSubstitute:

You can view the code examples from this blog post at https://github.com/hlaueriksson/ConductOfCode