Dependency injection for NServiceBus handler unit testing
Asked Answered
C

1

6

This is how you supposed to inject dependencies for your NServiceBus handler to test it:

Test.Handler<YourMessageHandler>()
  .WithExternalDependencies(h => h.Dependency = yourObj)

(http://nservicebus.com/UnitTesting.aspx)

However it means my Dependency object reference should be public that I do not like a much. Is any way to keep it private readonly and assign it inside constructor, so that implementation supposed to be passed through the handler constructor only?

Thanks

Catlin answered 8/6, 2012 at 21:40 Comment(0)
E
5

You can use constructor injection by using the following syntax:

 Test.Handler<YourMessageHandler>(bus => new YourMessageHandler(dep1, dep2))

Where dep1 and dep2 are in all likelihood just some stubs or mocks that your mocking framework cooked up for you.

-- Updated by Udi Dahan from here:

You can access the mocked bus instance via Test.Bus.

Ermina answered 8/6, 2012 at 21:48 Comment(6)
I tried this approach, but the problem is IBus property of my handler happens to be null in the case, I need it to be initialized properlyCatlin
Do you mean referencing IBus in the handler? Is it not possible to add a constructor parameter for that? You should be able to simply do something to the effect of public YourMessageHandler(IDependency dep1, IOtherDependency dep2, IBus bus) and simply assign it from there. Apologies if I'm missing something obvious, I've just never had any problems getting the references I needed with this before.Ermina
right, inside the handler Bus.Send<>(...) is used, so I need to verify its execution. The problem is I have no idea how to instantiate the property of IBus type, it supposed to be done magically by NServiceBus, I do not even see any public implementation of the interface, there is no 'Bus' class or something. I mean it is something hidden from us developers by NServiceBus libraryCatlin
I usually mock all the dependencies for unit tests, this includes the IBus. And yes, I'd also put IBus in the constructor and inject it there. (Rhino Mocks - MockRepository.GenerateStub<IBus>())Holocaust
dtryon, like I said, my purpose is to verify IBus's Send method invocations with a proper parameters values (see ExpectSend method), so I need NServiceBus mock it on its own. The second thing about mocking IBus is I do not know what kind of real object to be used to map it to, coz StructureMap will do invoke this constructor in runtime and I need to inform StructureMap on which particular class to be used for IBus interface: x.For<IBus>().Use<???>()Catlin
to use the bus instance as one of the constuctor dependencies, just simply do: Test.Handler<YourMessageHandler>(bus => new YourMessageHandler(dep1, bus, dep2))Maley

© 2022 - 2024 — McMap. All rights reserved.