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

时间:2019-03-17 17:46:37

标签: java junit

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

TestFeedService接口对象(testService)的值在testService.sendMessage(dataBO,false)调用中显示为null。这是我在测试用例中调用的方法中的内容。我不确定为什么会这样。我尝试在setup()中创建对象,但仍然失败。有人可以帮我吗?

下面是测试用例代码

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

1 个答案:

答案 0 :(得分:0)

您需要将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
}}

希望有帮助