Sina Salmani
Sina Salmani

Reputation: 99

Unit Testing Mock Service Impl

I have a service and serviceImpl too in a spring boot application. When I want to test it and trying to mock my service in junit test class I got NullPointerException error.

here is my service impl

package com.test;

import java.util.Date;

public class MyServiceImpl implements MyService {
    @Override
    public MyObject doSomething(Date date) {
        return null;
    }
}

and here is my test class

package com.test;

import com.netflix.discovery.shared.Application;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.jupiter.api.Assertions.assertNull;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application-integrationtest.properties")
class MyServiceImplTest {

    @Mock
    MyService myservice;

    @Test
    void doSomethingTest() {
        assertNull(myservice.doSomething(null));
    }
}

Upvotes: 1

Views: 3484

Answers (1)

Andronicus
Andronicus

Reputation: 26076

You need to initialize your mocks, when using @Mock annotations. You can do it in method annotated with @Before:

@Before public void initMocks() {
    MockitoAnnotations.initMocks(this);
}

Alternatively you can change your runner from SpringRunner to:

@RunWith(MockitoJUnitRunner.class)

Edit:

Also you have to create a bean from your implementation:

@Service
public class MyServiceImpl implements MyService

Upvotes: 4

Related Questions