使用Junits测试springboot应用程序(测试需要自动连接构造函数的类的方法)



我有以下类,需要使用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,它从resources文件夹读取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构造函数时,它会显示为null。无论在哪里使用fileStorageProperties,都会导致java.lang.NullPointerException。我是java新手(刚刚1个月的exp(任何见解都会有所帮助。USing java 1.8和SpringJUnit4

我可以通过设置类中的字段来继续,这些字段在我的构造函数中是期望的:

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

Mockito@InjectMocks

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

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

替换为

@InjectMocks
private MyStorageService fileStorageService;

最新更新