【发布时间】:2021-12-15 13:32:44
【问题描述】:
我正在尝试学习使用 Spring 5、Mockito 和 JUnit 5 进行测试。 我有一个小的普通控制器类,它的测试如下:
@Controller
@RequestMapping("/customer")
public class CustomerController {
@Autowired
CustomerService customerService;
@Autowired
CustomerForm customerForm;
@GetMapping("/index")
public ModelAndView index(){
String customerName = customerService.getCustomerById(14).getFirstname(); <-- Giving me error here
customerForm.setCustomerName(customerName);
ModelAndView modelAndView = new ModelAndView("customer/pages/customer/Home");
modelAndView.addObject("customerForm", customerForm);
return modelAndView;
}
}
@ExtendWith(MockitoExtension.class)
class CustomerControllerTest {
@InjectMocks
CustomerController customerController;
@Mock
CustomerServiceImpl customerService;
@Mock
CustomerForm customerForm;
Customer customer;
String customerName;
@SuppressWarnings("deprecation")
@BeforeEach
void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
customer = new Customer(14, "John");
customerName = "John";
}
@Test
void testIndex() {
int customerId = 14;
when(customerService.getCustomerById(customerId).getFirstname()).thenReturn(customerName); <-- Giving me error here, NullPointerException
customerForm.setCustomerName(customerName);
ModelAndView mav = customerController.index();
assertEquals( customerForm, mav.getModel().get("customerForm"));
}
}
错误:
java.lang.NullPointerException
at com.primis.controller.CustomerControllerTest.testIndex(CustomerControllerTest.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
当我运行这个测试时,我得到了NullPointerException,如图所示。
请有人指出我正确的方向,我做错了什么。
谢谢
【问题讨论】: