猿问

在对象的 Junit 测试用例中获取 NullPointerException

我是Java的新手,尝试了各种方法来解决这个问题,但没有运气。


TestFeedService 接口对象 (testService) 值在 testService.sendMessage(dataBO, false) 调用时显示为 null。这存在于我从测试用例调用的方法中。我不知道为什么会发生这种情况。我尝试在 setup() 中创建 Object,但仍然失败。有人可以帮我吗?


下面是测试用例代码


public class testApiControllerTest {

private MockMvc mockMvc;

private TesApiController testApiController;

private TestFeedService testService;


@Before

public void setup() {

  testApiController = mock(TestApiController.class);

  testService = mock(TestFeedService.class);

  testService = new TestFeedServiceImpl();

}


@Test

public void testProcessMessage() {

  TestApiController testApiController = new TestApiController();

  TestForm2 testForm2 = new TestForm2();

  testForm2.setType("PROMO_CODE");

  testForm2.setUserId("1");

  testForm2.setMessage("Welcome");

  ResponseEntity<?> responseEntity = testApiController.processMessage(testForm2);

  assertEquals(HttpStatus.OK, responseEntity.getStatusCode());

}}

Java 代码:


  public class TestApiController {

@Autowired

private TestFeedService testService; // This is an interface 


@RequestMapping(path = "/api/process-message", method = RequestMethod.POST)

public ResponseEntity<?> processMessage(@RequestBody TestForm2 testForm) {

  DataBO dataBO = convertBO(testForm);

  testService.sendMessage(dataBO, false);  // here I am getting testService = null and causing exception

  return ResponseEntity.ok().build();

} // Some more code


蝴蝶不菲
浏览 185回答 1
1回答

慕无忌1623718

您需要将 TestService 放在 TestApiController 的构造函数中,以便在测试中创建对象时可以注入它。public class TestApiController {private TestFeedService testService; // This is an interface&nbsp;@Autowiredpublic TestApiController(TestFeedService testService ) {&nbsp; &nbsp; this.testService = testService;}@RequestMapping(path = "/api/process-message", method = RequestMethod.POST)public ResponseEntity<?> processMessage(@RequestBody TestForm2 testForm) {&nbsp; DataBO dataBO = convertBO(testForm);&nbsp; testService.sendMessage(dataBO, false);&nbsp; // here I am getting testService = null and causing exception&nbsp; return ResponseEntity.ok().build();} // Some more code所以你的测试是这样的:public class testApiControllerTest {private MockMvc mockMvc;private TesApiController testApiController;private TestFeedService testService;@Beforepublic void setup() {&nbsp; this.testService = mock(TestFeedService.class);}@Testpublic void testProcessMessage() {&nbsp; this.testApiController = new TestApiController(this.testService);&nbsp; // More code}}希望它有帮助
随时随地看视频慕课网APP

相关分类

Java
我要回答