当前位置: 首页 > 知识库问答 >
问题:

Spring测试中的NullPointerException with Service,尽管参数已经有一个值

微生自怡
2023-03-14

我想在服务类中测试一个方法,但是如果(!uploadFolder.endswith(“/”))uploadFolder+=“/”行中有NullPointerException,尽管uploadFolder已经有一个有效值。测试类中uploadFolder的模拟值取自Application.yml文件。MockMultipartFile也成功创建,其中包含内容。

服务类别:

@Service
public class UploadService {
  private static File uploadedDocument;

  @Value("${directory.upload}")
  private String uploadFolder;

  public ResponseEntity saveFile(MultipartFile file) {
    if (!uploadFolder.endsWith( "/" )) uploadFolder += "/";
    try {
        File saveDir = new File( uploadFolder );

        if (!saveDir.exists()) {
            if (!saveDir.mkdirs())
                return ResponseEntity.status( HttpStatus.FORBIDDEN ).body( "No permission to write." );
        }
        byte bytes[] = file.getBytes();
        Path path = Paths.get( uploadFolder + file.getOriginalFilename() );
        Files.write( path, bytes );
        File myFile = new File( uploadFolder, file.getOriginalFilename() );

        uploadedDocument = myFile;

        return ResponseEntity.status( 200 ).build();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return ResponseEntity.status( 500 ).build();
}

测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource("classpath:application.yml")
@ActiveProfiles("test")
public class UploadServiceTest {

  private UploadService uploadService;

  @Value("${directory.upload}")
  private String uploadFolder;

  @Before
  public void before() {
    uploadService = new UploadService();
    System.out.println( uploadFolder );
  }

  @Test
  public void testSaveFile() throws Exception {
    byte[] content = Files.readAllBytes( Paths.get( uploadFolder + "\\test.txt" ) );
    MockMultipartFile mockMultipartFile = new MockMultipartFile( "document", content );
    ResponseEntity response = uploadService.saveFile( mockMultipartFile );
    Assert.assertEquals( response, new ResponseEntity( HttpStatus.ACCEPTED ) );
  }

}

共有1个答案

归建安
2023-03-14

您的UploadFolder变量仅加载在测试类中。这就是为什么要得到NullPointerException。如果执行测试,则uploadservice中的uploadfolder仍然为空。

只要可能,我都不会在测试中使用spring上下文。在您的示例中,可以将测试作为普通的junit测试运行,并使用Spring中的ReflectionTestUtils类设置UploadServiceUploadFolder变量。在测试类的before-method中添加以下行:

RectionTestUtils.setField(uploadService, "uploadFolder", "your_folder_path");

参见ReflectionTestUtils类的JavaDoc:JavaDoc:ReflectionTestUtils.SetField(java.lang.Object,java.lang.String,java.lang.Object)

 类似资料:
  • 参数化测试可以将不同的数据输入到测试中。不过,我创建了一个示例计算器,希望为其创建参数化测试。但是,我发现您只能为单个测试创建一组参数化数据。 我已经创建了参数化测试,用于添加两个数字,得到预期的结果。由于预期结果会有所不同,因此该数据将不适用于减法运算。 有没有可能为每个加、减、乘、除测试提供参数化数据? 非常感谢您的建议,

  • 我完全不知所措,我不明白这里出了什么问题。我正在编写一个Java程序来获取一些数据库并将它们放入mySQL数据库中。我在构建路径中找到了JConnector: 构建路径截图 当我运行这段代码时,输出是: 当我删除地址的"? user=root"部分时,它会给我: 这意味着,如果我无法连接到数据库,它将抛出异常,因此它显然正在连接,但它表示没有选择任何数据库,尽管我只是在几行前连接到它。事实上,返回

  • 我们有一个bean公司处理器。在Spring引导集成测试中,当这个bean中的方法抛出异常时,我们想测试一个异常场景。 因此,我们创建了一个覆盖bean TestCompanyProcencer,它扩展了CompanyProcencer。TestCompanyProcencer标记为@主要。当我们只运行这个测试类时,测试运行正常,被覆盖的bean按预期使用。 但是这个测试类和其他几个测试类一起运行

  • 我想单击单击时下载文件的按钮,并测试是否已下载预期的文件。 我已经用谷歌搜索过这个,但不幸的是没有找到关于这个主题的任何具体答案,我找到的很多帖子都已经过时了(2014 年),我敢打赌 Selenium 现在一定已经改变了 API 定义。

  • 我是Java的新手,正在尝试解决初学者在给定数之后寻找下一个素数的问题。下面是我提出的解决方案的两个版本。对于第一个版本,编译器要求我包含第二个return语句(即return 0;)在findNextNumber方法的末尾,我已经在代码中包含了一个return语句,而第二个版本没有要求我包含一个额外的return语句。有人能告诉我为什么会这样吗?提前感谢您的帮助!