Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 初始化对象引用时出现NullPointerException-Junit测试方法_Java_Unit Testing_Mockito_Junit4_Powermock - Fatal编程技术网

Java 初始化对象引用时出现NullPointerException-Junit测试方法

Java 初始化对象引用时出现NullPointerException-Junit测试方法,java,unit-testing,mockito,junit4,powermock,Java,Unit Testing,Mockito,Junit4,Powermock,我有一个需要进行单元测试的方法“validateFile()”。该方法返回一个用户定义类型的引用。此引用是使用另一个方法“M”返回的值设置的。此方法“M”被模拟并返回模拟结果。但是,设置该引用会引发NullPointerException。 代码如下所示: @RunWith(PowerMockRunner.class) @PrepareForTest({ExcelValidations.class, MiscellaneousService.class}) class TestClass

我有一个需要进行单元测试的方法“validateFile()”。该方法返回一个用户定义类型的引用。此引用是使用另一个方法“M”返回的值设置的。此方法“M”被模拟并返回模拟结果。但是,设置该引用会引发NullPointerException。 代码如下所示:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ExcelValidations.class, MiscellaneousService.class})    
class TestClass(){

@Test
public void sampleTest(){
  ExcelSheetIngestion excelSheetIngestion = new ExcelSheetIngestion();
  PowerMockito.mockStatic(MiscellaneousService.class);
  Mockito.when(MiscellaneousService.getRandomString()).thenReturn("mockedString123");

  FileResponse response = excelSheetIngestion.validateFile(streamTest);
  Assert.assertNotEquals("null",response.getBatchId());

}

class ExcelSheetIngestion(){

  @Inject 
  FileUploadResponse  response;
  //The method to be tested
  public FileResponse validateFile(){

  String randomString = MiscellaneousService.getRandomString();//mocked and return mockedString123
  response.setBatchId(randomString);//throws exception at this point
  response.setError(errorList); 
  return response;
  }
}

任何关于我哪里出错的线索都会很有帮助。

它看起来像是在
validateFile()
中,您正在使用
response
字段,但我们看不到您何时初始化它。在
sampleTest
中,您创建了
FileResponse=…
但这会创建局部变量。哎呀,我刚刚编辑了我的代码。这两种方法中都应该是FileResponse。我添加了一个注释,其中异常是thrown,您在哪里初始化摄取?或者streamTest?它在测试方法中初始化。抱歉,刚才编辑了代码。请确认您的测试类上有
@RunWith(PowerMockRunner.class)
@PrepareForTest(MiscellaneousService.class)
注释,好吗?