Testing springboot applications using Junits (Test methods for classes which require constructors that were autowired)

huangapple go评论90阅读模式
英文:

Testing springboot applications using Junits (Test methods for classes which require constructors that were autowired)

问题

以下是翻译好的内容:

@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("创建目录时出现内部错误:{}", ex);
            throw new FileStorageException("创建目录时出现内部错误", ex);
        }
    }
    public String storeFile(String destination, MultipartFile file) {
    // 对文件系统执行一些复制和存储操作//
    }
}
@ConfigurationProperties(prefix = "file")
public class FileStorageProperties {
    private String uploadDir;

    public String getUploadDir() {
        return uploadDir;
    }

    public void setUploadDir(String uploadDir) {
        this.uploadDir = uploadDir;
    }
}
@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() {
    //断言文件创建逻辑和storeFile方法逻辑//
    }

    @EnableConfigurationProperties(FileStorageProperties.class)
    public static class TestConfiguration {
        // 无内容
    }
}

在我的翻译中,我仅提供了你所要求的代码翻译部分,没有包含其他内容。如果你有任何进一步的问题或需要其他帮助,请随时提问。

英文:

I have the following class which I need to test using 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//
    }
}

I have the dependent bean FileStorageProperties as given below which reads application.properties from resources folder to get root directory path:

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

    public String getUploadDir() {
        return uploadDir;
    }

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

    }
}

I have sample Junit which I am struggling to complete

@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
    }
}

I need to come up with the correct way to setup my testClass, don't want the logic for the unit test case.
When I try to inject fileStorageProperties into MyStorageService constructor it comes as null.
Which will cause java.lang.NullPointerException wherever fileStorageProperties is used.
I am new to java (barely 1 month exp)
Any insight would be helpful.
USing java 1.8 and SpringJUnit4

答案1

得分: 1

我能够继续操作,通过设置在我的构造函数中所需的类中的字段:

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

I was able to proceed by setting the fields in my class which were expected in my constructer:

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

答案2

得分: 0

Mockito @InjectMocks

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

> 1. 基于构造函数的注入 - 当类中定义了构造函数时,Mockito会尝试使用最大的构造函数来注入依赖项。
> 2. 基于Setter方法的注入 - 当没有定义构造函数时,Mockito会尝试使用setter方法来注入依赖项。
> 3. 基于字段的注入 - 如果没有构造函数或无法进行基于字段的注入,则Mockito会尝试将依赖项注入到字段本身。

@InjectMocks
private MyStorageService fileStorageService;

替换为

@InjectMocks
private MyStorageService fileStorageService;
英文:

Mockito @InjectMocks

Mockito tries to inject mocked dependencies using one of the three approaches, in the specified order.

> 1. Constructor Based Injection – when there is a constructor defined for the class, Mockito tries to inject dependencies using the biggest
> constructor.
> 2. Setter Methods Based – when there are no constructors defined, Mockito tries to inject dependencies using setter methods.
> 3. Field Based – if there are no constructors or field-based injection possible, then mockito tries to inject dependencies into the field
> itself.

@InjectMocks
private MyStorageService fileStorageService = new MyStorageService(fileStorageProperties);

Replace With

@InjectMocks
private MyStorageService fileStorageService;

huangapple
  • 本文由 发表于 2020年4月8日 02:16:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/61086714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定