Java 初始化对象引用时出现NullPointerException-Junit测试方法
我有一个需要进行单元测试的方法“validateFile()”。该方法返回一个用户定义类型的引用。此引用是使用另一个方法“M”返回的值设置的。此方法“M”被模拟并返回模拟结果。但是,设置该引用会引发NullPointerException。 代码如下所示: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
@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)
注释,好吗?