1

我在 Spring Boot 应用程序中也有一个 service 和 serviceImpl 。当我想测试它并尝试在 junit 测试类中模拟我的服务时,我得到了NullPointerException错误。

这是我的服务 impl

package com.test;

import java.util.Date;

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

这是我的测试课

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));
    }
}
4

1 回答 1

4

@Mock使用注释时,您需要初始化模拟。您可以在使用以下注释的方法中执行此操作@Before

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

或者,您可以将跑步者从更改SpringRunner为:

@RunWith(MockitoJUnitRunner.class)

编辑:

您还必须从您的实现中创建一个 bean:

@Service
public class MyServiceImpl implements MyService
于 2019-03-12T06:45:23.677 回答