3
pleuph
6y

Unit testing with NSubstitute and Autofac
For the most part, I find it a lot simpler than SimpleInject (hmm) and Moq, which I have used previously.

But there are still some of those 'Oh, for fucks sake!'-gotchas.

I was trying to test a class today where I wanted to substitute all other methods in the class than the one I wanted to test == an actual unit test.

I had previously found out how to do this:

1. Make sure the methods that should be substituted are internal to allow substitution.

2. Substitute class with Substitute.ForPartsOf<T>(args)

3. Set up methods that should not be called with instance.When(a => a.Method()).DoNotCallBase()

This way, you can unit test a class properly and only call the method that you want to test, and also control the return values of the other methods if needed.

So as I said, I have used this before to great effect. But today I just could NOT get it to work! I checked and rechecked everything but the test code kept calling the implementations of the substituted methods!

I even called over another dev for help, but he couldn't see the problem either.

Aargh!

I scoured the internet, but everyone just told me what I already knew: follow the 3 steps, and all is well. Not so!

I ALMOST considered doing the test improperly, as in, increasing the scope beyond that of the method I wanted to test.

But then it hit me... My project was missing this line in AssemblyInfo.cs:

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

I always add a line to make internals visible to the test project, but I had forgotten that NSubstitute needs this line as well to work properly.

Sometimes when a test fails it will tell you that you are missing this line. And sometimes it just doesn't work.

Maybe I will remember this in the future now. Maybe 😅

Comments
Add Comment