Java 单元测试模拟服务Impl
我在spring引导应用程序中也有一个service和serviceImpl。当我想测试它并试图在junit测试类中模拟我的服务时,我得到了Java 单元测试模拟服务Impl,java,spring,unit-testing,spring-boot,mockito,Java,Spring,Unit Testing,Spring Boot,Mockito,我在spring引导应用程序中也有一个service和serviceImpl。当我想测试它并试图在junit测试类中模拟我的服务时,我得到了NullPointerExceptionerror 这是我的服务impl package com.test; import java.util.Date; public class MyServiceImpl implements MyService { @Override public MyObject doSomething(Date
NullPointerException
error
这是我的服务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));
}
}
使用
@Mock
注释时,需要初始化Mock。您可以在前面用@注释的方法中执行此操作:
@Before public void initMocks() {
MockitoAnnotations.initMocks(this);
}
或者,您可以将跑步者从SpringRunner
更改为:
@RunWith(MockitoJUnitRunner.class)
编辑:
此外,还必须从实现中创建bean:
@Service
public class MyServiceImpl implements MyService
使用@Mock
注释时,需要初始化Mock。您可以在前面用@注释的方法中执行此操作:
@Before public void initMocks() {
MockitoAnnotations.initMocks(this);
}
或者,您可以将跑步者从SpringRunner
更改为:
@RunWith(MockitoJUnitRunner.class)
编辑:
此外,还必须从实现中创建bean:
@Service
public class MyServiceImpl implements MyService
myservice对象为空yetThanks,感谢您的回复。但它还不起作用。我加了@Service。然后添加@Before方法。不起作用。将@RunWith参数更改为MockitoJUnitRunner
并添加服务。不起作用您可以粘贴整个类,其中@SpringBootApplication
是?@SpringBootApplication公共类矛盾应用程序{public static void main(String[]args){TimeZone.setDefault(TimeZone.getTimeZone(“UTC”));SpringApplication.run(矛盾application.class,args);}}
这就是为什么我要问编辑问题。您需要将服务和impl移动到矛盾应用程序的子包中
myservice对象为null Yet感谢您的回复。但它还不起作用。我加了@Service。然后添加@Before方法。不起作用。将@RunWith参数更改为MockitoJUnitRunner
并添加服务。不起作用您可以粘贴整个类,其中@SpringBootApplication
是?@SpringBootApplication公共类矛盾应用程序{public static void main(String[]args){TimeZone.setDefault(TimeZone.getTimeZone(“UTC”));SpringApplication.run(矛盾application.class,args);}}
这就是为什么我要问编辑问题。您需要将服务和impl移动到矛盾应用程序的子包中
我用您的代码进行了测试,没有引发异常…我用您的代码进行了测试,没有引发异常。。。