Lorenzo D'Isidoro
Lorenzo D'Isidoro

Reputation: 2219

Testing Spring service class which uses an Autowired object

I have to test a Spring service which uses an Autowired object, see the following code:

@Service
public class MyService {

    @Autowired
    ExternalService externalService;

    public String methodToTest(String myArg) {
        String response = externalService.call(myArg);
        // ...
        return ...;
    }

What I tried to do in my test class, using Mockito, is to mock the externalService's call method as follows:

@ExtendWith(MockitoExtension.class)
public class MySeviceTest {
    @Mock
    private ExternalService externalService = Mockito.mock(ExternalService.class);
    private MySevice mySevice = Mockito.spy(new MySevice());

    @Test
    public void methodToTest_Test() {
        Mockito.when(externalService.call(anyString())).thenReturn(anyString());
        // ...
    }
}

The problem is at runtime in the class MyService because the externalService object is null, and as a result I get the null pointer exception. So, what's the right method to write this type of test?

Upvotes: 0

Views: 31

Answers (1)

Ascendise
Ascendise

Reputation: 221

You get a null pointer exception because you did not set the property 'externalService'. @Autowired only works when running with Spring. For your test you have to inject your mock yourself:

@ExtendWith(MockitoExtension.class)
public class MySeviceTest {
    @Mock
    private ExternalService externalService = Mockito.mock(ExternalService.class);
    private MySevice mySevice = Mockito.spy(new MySevice());

    @Test
    public void methodToTest_Test() {
        myService.externalService = externalService //inject your mock via the property
        Mockito.when(externalService.call(anyString())).thenReturn(anyString());
        // ...
    }
}

Upvotes: 1

Related Questions