我完全被难住了。我是SpringBatch测试的新手,我发现了无数让我感到困惑的例子。
我正在尝试测试Spring Batch决策器。此判定器在继续之前检查是否存在某些JSON文件。
首先,我在Spring Batch项目中有一个BatchConfiguration文件,标记为@Configuration。
在BatchConfiguration中,我有一个ImportJsonSettingsbean,它从application.properties文件中的设置加载其属性。
@ConfigurationProperties(prefix="jsonfile")
@Bean
public ImportJSONSettings importJSONSettings(){
return new ImportJSONSettings();
}
当运行SpringBatch应用程序时,这可以完美地工作。
接下来,这里是JsonFilesExistDecider的基础,它自动连接FileRetriever对象。。。
public class JsonFilesExistDecider implements JobExecutionDecider {
@Autowired
FileRetriever fileRetriever;
@Override
public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) { ... }
FileRetriever对象本身自动连接ImportJSONSettings。
这是FileRetriever。。。
@Component("fileRetriever")
public class FileRetriever {
@Autowired
private ImportJSONSettings importJSONSettings;
private File fieldsFile = null;
public File getFieldsJsonFile(){
if(this.fieldsFile == null) {
this.fieldsFile = new File(this.importJSONSettings.getFieldsFile());
}
return this.fieldsFile;
}
}
现在是测试文件。我正在使用Mockito进行测试。
public class JsonFilesExistDeciderTest {
@Mock
FileRetriever fileRetriever;
@InjectMocks
JsonFilesExistDecider jsonFilesExistDecider;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testDecide() throws Exception {
when(fileRetriever.getFieldsJsonFile()).thenReturn(new File(getClass().getResource("/com/files/json/fields.json").getFile()));
// call decide()... then Assert...
}
}
问题。。。FileRetriever对象中的@Autowired的ImportJSONSETTING对象始终为NULL。
当调用testDecide((方法时,我会得到一个NPE,因为在FileRetriever中调用getFieldsJsonFile((所以ImportJSONSettingsbean不存在。
如何在FileRetriever对象中正确创建ImportJSONSettingsbean,以便使用它??
我尝试将以下内容添加到我的测试类中,但没有帮助。
@Mock
ImportJSONSettings importJSONSettings;
我需要独立创建它吗?它是如何被注入FileRetriever的?
如有任何帮助,我们将不胜感激。
尝试将setup()
方法上的@Before
注释更改为@BeforeEach
,如下所示:
@BeforeEach
void setup() {
MockitoAnnotations.initMocks(this);
}
这也可能是一个依赖性问题。请确保您有最新版本的io.micrometer:micrometer-core
。你能分享你的测试依赖关系吗?
如果您正确地进行了上述设置,那么只要您正确地存根了getFieldsJsonFile()
,就不必担心ImportJSONSettings
是否为null。