0

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?

1 Answer 1

1

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());
        // ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.