【发布时间】: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