在 Mockito Junit 中@InjectMocks后为空



在使用 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));
}
}

尝试调用

MockitoAnnotations.initMocks(this);

在您的测试方法或@Before setup(( 方法中

最新更新