亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在對象的 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 關注
  • 208 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號