rocky
rocky

Reputation: 831

How to inject real objects through InjectMocks annotation

I have scenario where there are two properties in a class, where one property in real and other one is mock how to inject both the properties to the object.

For example.

    @RunWith(MockitoJUnitRunner.class)
    public class SampleTest extends ExchangeTestSupport {

        @InjectMocks
        private SampleTest sampleTest ;

        private SampleProperties properties;
        @Mock
        private SampleProvider provider;
}

In above code properties is real and provider is mock and need to inject both to sampleTest object.

Upvotes: 10

Views: 7868

Answers (1)

Ori Marko
Ori Marko

Reputation: 58772

Add @Spy to inject real object

 @Spy
 private SampleProperties properties;

A field annotated with @Spy can be initialized explicitly at declaration point. Alternatively, if you don't provide the instance Mockito will try to find zero argument constructor (even private) and create an instance for you.

If you are using Spring context, also add @Autowired annotation

Upvotes: 8

Related Questions