I have a class and I am injecting a proxy into my service.
Service service
{
private ServiceProxy proxy;
public Service(ServiceProxy proxy)
{
Write your test class as this, which will initialize Service
with a mock of ServiceProxy
:
class ServiceTest
{
@Mock
ServiceProxy mockProxy;
//This will inject the "ServiceProxy" mock into your "Service" instance.
@InjectMocks
Service service = new Service(mockProxy);
@Before
public void init() {
//This will initialize the annotated mocks
MockitoAnnotations.initMocks(this);
}
@Test
public void test() {
...
}
}
Provided you are using Mockito version 1.9.0 or later, the best way to achieve what you want is like this:
@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
@Mock
private ServiceProxy proxy;
@InjectMocks
private Service service;
@Test
public void test() {
assertNotNull(service);
assertNotNull(proxy);
}
}
First thing is the @RunWith(MockitoJUnitRunner.class)
declaration which will cause @Mock and @InjectMocks annotation to work automatically without any explicit initialization. The second thing is that starting with Mockito 1.9.0 @InjectMocks annotation can use the Constructor injection mechanism which is the best option for your Service class.
Other options for @InjectMocks are Setter injection and Field injection (see docs BTW) but you'd need a no argument constructor to use them.
So summarizing - your code cannot work because:
If for some reason you don't want to use @InjectMocks, the only way is to construct your Service object within the test method body or within the @Before annotated setUp method.