【问题标题】:Testing springboot applications using Junits (Test methods for classes which require constructors that were autowired)使用 Junit 测试 Spring Boot 应用程序(需要自动装配的构造函数的类的测试方法)
【发布时间】:2020-04-07 18:16:51
【问题描述】:

我有以下需要使用 Junits 测试的类

@Service
public class MyStorageService {
    private final Path fileStorageLocation;

    @Autowired
    public MyStorageService(FileStorageProperties fileStorageProperties) {
        fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir()).toAbsolutePath().normalize();

        try {
            Files.createDirectories(this.fileStorageLocation);
        } catch (Exception ex) {
            logger.error("An Internal error occurred when creating directories: {}", ex);
            throw new FileStorageException("An Internal error occurred when creating directories", ex);
        }
    }
    public String storeFile(String destination, MultipartFile file) {
    //Does some copy and storage operations on file system//
    }
}

我有下面给出的依赖 bean FileStorageProperties,它从资源文件夹中读取 application.properties 以获取根目录路径:

@ConfigurationProperties(prefix = "file")
public class FileStorageProperties {
    private String uploadDir;

    public String getUploadDir() {
        return uploadDir;
    }

    public void setUploadDir(String uploadDir) {
        this.uploadDir = uploadDir;

    }
}

我有我正在努力完成的示例 Junit

@RunWith(SpringRunner.class)
@TestPropertySource(locations = "classpath:test.properties")
@SpringBootTest(classes = {MyStorageServiceTests.TestConfiguration.class})
public class MyStorageServiceTests {
    @MockBean
    private FileStorageProperties fileStorageProperties;
    @InjectMocks
    private MyStorageService fileStorageService = new MyStorageService(fileStorageProperties);


    @Test
    public void testFileLocationCreation() {
    //assert file created logic and storeFile method logic//
    }

    @EnableConfigurationProperties(FileStorageProperties.class)
    public static class TestConfiguration {
        // nothing
    }
}

我需要想出正确的方法来设置我的 testClass,不想要单元测试用例的逻辑。 当我尝试将 fileStorageProperties 注入 MyStorageService 构造函数时,它为空。 无论在哪里使用 fileStorageProperties,这都会导致 java.lang.NullPointerException。 我是 Java 新手(只有 1 个月的经验) 任何见解都会有所帮助。 使用 java 1.8 和 SpringJUnit4

【问题讨论】:

    标签: java spring spring-boot junit


    【解决方案1】:

    我可以通过在我的类中设置构造函数中预期的字段来继续:

        @Autowired
        private FileStorageProperties fileStorageProperties;
        ReflectionTestUtils.setField(fileStorageProperties, "uploadDir",    source.getAbsolutePath());
        MyStorageService myStorageService = new myStorageService(fileStorageProperties);
    

    【讨论】:

      【解决方案2】:

      Mockito @InjectMocks

      Mockito 尝试使用三种方法之一,按照指定的顺序注入模拟依赖项。

      1. 基于构造函数的注入 - 当为类定义了构造函数时,Mockito 尝试使用最大的注入依赖项 构造函数。
      2. 基于 Setter 方法 - 当没有定义构造函数时,Mockito 会尝试使用 setter 方法注入依赖项。
      3. 基于字段 - 如果没有构造函数或基于字段的注入可能,则 mockito 尝试将依赖项注入字段 本身。
      @InjectMocks
      private MyStorageService fileStorageService = new MyStorageService(fileStorageProperties);
      

      替换为

      @InjectMocks
      private MyStorageService fileStorageService;
      

      【讨论】:

      • 我收到以下错误:org.mockito.exceptions.base.MockitoException: Cannot instantiate @InjectMocks field named 'fileStorageService' of type 'class com.nokia.fileuploadservice.service.FileStorageService'. You haven't provided the instance at field declaration so I tried to construct the instance. However the constructor or the initialization block threw an exception : null 这是因为我的构造函数"` fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir()).toAbsolutePath().normalize();` 其中 fileStorageProperties 是仍然为空
      猜你喜欢
      • 2016-10-10
      • 2017-02-25
      • 2020-02-09
      • 2021-12-23
      • 1970-01-01
      • 2013-09-28
      • 2014-07-30
      • 1970-01-01
      • 2018-07-22
      相关资源
      最近更新 更多