【发布时间】:2020-01-05 16:39:06
【问题描述】:
在使用 JUnit 进行单元测试时,我在传递依赖项时遇到了一些麻烦。
考虑这些代码:
这是我要测试的类的依赖注入,我们称之为服务。
错误日志跟踪
java.lang.NullPointerException
at com.example.demo.service.ServiceClass.getCustomerById(ServiceClass.java:50)
at com.example.demo.service.ServiceClassTest.getCustomerByIdTest(ServiceClassTest.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
服务类
@Service
public class ServiceClass {
public static final String CRM_JPA_URI = "http://localhost:9000/api/tickets/";
@Autowired
RestTemplate restTemplate;
public Customer getCustomerById(int customerId) {
ResponseEntity<Customer> entity = restTemplate.getForEntity(CRM_JPA_URI +"ticket/{customerId}",
Customer.class, customerId);
return entity.getBody();
}
}
服务类测试
@RunWith(MockitoJUnitRunner.class)
public class ServiceClassTest {
@Mock
RestTemplate mockRestTemplate;
@InjectMocks
ServiceClass serviceClass;
/**
* getCustomerByIdTest
*/
@Test
public void getCustomerByIdTest(){
Customer customer = new Customer();
customer.setPassengerName("Ramesh");
customer.setBookingDate("09/09/2019");
customer.setDestStation("pamur");
customer.setEmail("r@gmail.com");
customer.setSourceStation("ongole");
Mockito.lenient().when(mockRestTemplate.getForEntity("http://localhost:9000/api/tickets/ticket/1", Customer.class)).
thenReturn(new ResponseEntity<Customer>(customer,HttpStatus.OK));
System.out.println("object is--->"+serviceClass.getCustomerById(1));
assertEquals(customer, serviceClass.getCustomerById(1));
}
}
【问题讨论】:
-
你的问题是什么?
-
在测试类中调用服务类时出现空指针异常
-
而异常的堆栈跟踪是?
-
@JB Nizet 我用堆栈跟踪编辑了我的问题
-
你需要逻辑推理。只能抛出异常,因为
entity为空。那为什么它是空的?因为restTemplate.getForEntity(...)返回null?为什么它返回null?因为您没有告诉模拟休息模板在使用这些参数调用此方法时要返回什么。查看代码中的 URL。查看测试中的 URL。它们不一样。
标签: spring-boot junit mockito