1

I have a Java application based on Spring that uses services. For some reasons, I need to autowire a service that is implemented just for the sake of unit testing. I would like this autowired class to be a Mockito mock, such that I can pass it to all the Mockito methods (when(), etc.). Should I extend or implement some Mockito class?

E.g.

@Profile("test")
@Primary
@Service
public class MockAService implements AService {
    public void callMethod(){}
}

Then in the test I have

{
    System.setProperty("spring.profiles.active", "test");
}

@Autowired AService aservice;

and in the test method I want to do:

@Test
public void test(){
  doNothing().when(aService).callMethod();
}
Community
  • 1
  • 1
JeanValjean
  • 17,172
  • 23
  • 113
  • 157
  • You probably could use bean overriding and for your test define an additional context and let it be merged with the original application context using [`@ContextConfiguration`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/ContextConfiguration.html) – SpaceTrucker Aug 31 '15 at 14:18

2 Answers2

2

Just use @Spy and in you @Before method call MockitoAnnotations.initMocks. It will create a spy for your injected services.

Exemple i want to test MyService and it has a dependecy on MyDao. I want MyService to use my mocked dao.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/com/stackoverflow/mokito/exemple/spring.xml"})
public class TestCase {
    @Resource
    @InjectMocks
    private MyService service;

    @Resource
    @Spy
    private MyDao dao;

    public void setup() {
        MockitoAnnotations.initMocks(this);
    }
}

However your spring context is now "dirty". The next test class will use the same spring context and MyService will still use the mock. So don't forget to reset mock in @After

JEY
  • 6,973
  • 1
  • 36
  • 51
0

A mock would even be better than a spy if you don't want the service to do anything. By default, calling the function on the mock won't do anything. With the spy, you have to explicitly call doNothing().

But why do you want to load any Spring context anyway ? Couldn't you mock all the services and test your class in full isolation ?

oailloud
  • 363
  • 1
  • 2
  • 7