Elad Benda
Elad Benda

Reputation: 36684

how to combine mock and DI in java?

I want to use a DI framework (e.g. Spring or GUICE)

do I have to wrap any Service-object with an interface in order to DI framework to work?

When I write UT,

can I combine a mocking framework with it (e.g. mockito)?

Are there any things I should pay attention to when combining mock FW and DI FW ?

I'm a bit confused because the DI FW is meant also to change the implementation from PROD to fake one. No?

Upvotes: 1

Views: 470

Answers (1)

luboskrnac
luboskrnac

Reputation: 24591

As @BoristheSpider mentioned in comment, you shouldn't spin up Spring context at all during unit testing. So you need to wire dependencies (faked or real) into testing object by yourself.

One possible approach is to use field injection + @Injection/@Spy/@Mock features of Mockito framework. See example here

Far better approach with spring is to use constructor injection. DI framework isn't using Reflection when wiring and creating beans.

In unit test you can pass faked or real dependencies via constructor.

I would suggest to do research around constructor vs field injection. You can start on my blog: http://lkrnac.net/blog/2014/02/promoting-constructor-field-injection/

Upvotes: 1

Related Questions