我在 spring boot 应用程序中也有一个服务和 serviceImpl。当我想测试它并尝试在 junit 测试类中模拟我的服务时,我遇到了 NullPointerException
错误。
这是我的服务实现
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));
}
}
最佳答案
当使用 @Mock
注解时,你需要初始化你的模拟。您可以在使用 @Before
注释的方法中执行此操作:
@Before public void initMocks() {
MockitoAnnotations.initMocks(this);
}
或者,您可以将运行器从 SpringRunner
更改为:
@RunWith(MockitoJUnitRunner.class)
编辑:
您还必须从您的实现中创建一个 bean:
@Service
public class MyServiceImpl implements MyService
关于java - 单元测试模拟服务实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55115561/