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

Community
  • 1
  • 1
YMC
  • 4,925
  • 7
  • 53
  • 83

1 Answers1

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.

Udi Dahan
  • 11,932
  • 1
  • 27
  • 35
tmesser
  • 7,558
  • 2
  • 26
  • 38
  • 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 properly – YMC Jun 08 '12 at 21:53
  • 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. – tmesser Jun 08 '12 at 22:00
  • 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 library – YMC Jun 08 '12 at 22:10
  • 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()`) – Davin Tryon Jun 08 '12 at 22:52
  • 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().Use??>()` – YMC Jun 08 '12 at 23:35
  • to use the bus instance as one of the constuctor dependencies, just simply do: Test.Handler(bus => new YourMessageHandler(dep1, bus, dep2)) – Dave Rael Mar 14 '13 at 12:55