使用Service测试Spring测试中的NullPointerException,尽管参数已经有值

时间:2018-02-23 12:13:15

标签: unit-testing spring-boot service properties

我想在服务类中测试一个方法但是在行中有NullPointerException(!uploadFolder.endsWith(" /"))uploadFolder + =" /"虽然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 ) );
  }

}

2 个答案:

答案 0 :(得分:0)

您的uploadFolder变量仅在您的测试类中加载。这就是你得到NullPointerException的原因。如果您执行测试,uploadFolder中的UploadService仍为空。

在可能的情况下,我不会在测试中使用spring上下文。在您的情况下,您可以将测试作为正常的junit测试运行,并将uploadFolder的{​​{1}}变量设置为spring UploadService类。将以下行添加到测试类中的before方法中:

ReflectionTestUtils

请参阅ReflectionTestUtils类的JavaDoc:JavaDoc: ReflectionTestUtils.setField(java.lang.Object, java.lang.String, java.lang.Object)

答案 1 :(得分:0)

P.VAN有重点。

UploadService中的 uploadFolder和UploadServiceTest中的uploadFolder是不同的对象。在这种情况下,您可以像这样更改测试用例,并且UploadService中的uploadFolder不为空。

@Autowire
private UploadService uploadService;

你可以像这样注入测试值。

@TestPropertySource(properties = {"directory.upload = testDir"})