Testing Umbraco Composers

Something I’ve been wanting to write a test for but haven't come around to yet is the Umbraco Composer that was introduced in version 8.

Before composers we had to have some sort of bootstrapper or container builder class where we registered all of our dependencies and this class had a tendency to become quite bloated and messy over time. This was solved in version 8 by letting each individual component and service be responsible for register themselves and their own dependencies in a so called IUserComposer.

If you’re not familiar with Composers you can read more about it on the official documentation.

Composing
For this example, I’ve created a dummy service that inherits an IService interface:

And I’ve added an IUserComposer to register my composer in the IoC container:

Now this service can be injected in any constructor and be used in my implementation code:

Behind the scenes
Looking at the Umbraco source code we see that composition.RegisterFor is basically just a wrapper that forward that call to the same method on the service register: _register.RegisterFor.

Testing
So what I want to test is whether the RegisterFor metod on the underlying service register gets called the way I expect it to, and this is done by mocking IRegister and Verify that RegisterFor<IService, Service> gets called and also that it gets a Lifetime.Transient since this is the default parameter in the composition.RegisterFor method. The result looks like this:

That’s it!
Now this test will verify two things for me:

  1. It will secure my composer in case me or any of my coworkers would fiddle with this composer in the future and screw up the registering by mistake.

  2. (Bonus) If the default Lifetime parameter would someday change in a future version of Umbraco, my test will fail and give me a heads up.

Hope it can be useful to someone.

Cheers friends! ❤️