为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

蝴蝶不菲 2022-08-17 16:03:00
我是Java的新手,尝试了各种方法来解决这个问题,但没有运气。TestFeedService 接口对象 (testService) 值在 testService.sendMessage(dataBO, false) 调用时显示为 null。这存在于我从测试用例调用的方法中。我不知道为什么会发生这种情况。我尝试在 setup() 中创建 Object,但仍然失败。有人可以帮我吗?下面是测试用例代码public class testApiControllerTest {private MockMvc mockMvc;private TesApiController testApiController;private TestFeedService testService;@Beforepublic void setup() {  testApiController = mock(TestApiController.class);  testService = mock(TestFeedService.class);  testService = new TestFeedServiceImpl();}@Testpublic 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 {@Autowiredprivate 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
查看完整描述

1 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

您需要将 TestService 放在 TestApiController 的构造函数中,以便在测试中创建对象时可以注入它。


public class TestApiController {


private TestFeedService testService; // This is an interface 


@Autowired

public TestApiController(TestFeedService testService ) {

    this.testService = testService;

}


@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

所以你的测试是这样的:


public class testApiControllerTest {

private MockMvc mockMvc;

private TesApiController testApiController;

private TestFeedService testService;


@Before

public void setup() {

  this.testService = mock(TestFeedService.class);

}


@Test

public void testProcessMessage() {

  this.testApiController = new TestApiController(this.testService);

  // More code

}}

希望它有帮助


查看完整回答
反对 回复 2022-08-17
  • 1 回答
  • 0 关注
  • 184 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信