我完全陷入了困境。我是Spring Batch测试的新手,我发现了无数的示例,这些示例让我感到困惑。
我正在尝试测试Spring Batch决策程序。该决定者在继续之前检查是否存在某些JSON文件。
首先,我在Spring Batch项目中有一个标记为@Configuration的 BatchConfiguration 文件。
在BatchConfiguration中,我有一个 ImportJsonSettings bean,该bean从 application.properties 文件中的设置加载其属性。
@ConfigurationProperties(prefix="jsonfile")
@Bean
public ImportJSONSettings importJSONSettings(){
return new ImportJSONSettings();
}
在运行Spring Batch应用程序时,它可以完美运行。
接下来,这是 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的 ImportJSONSettings 对象始终为NULL。
调用 testDecide()方法时,由于在FileRetriever中调用 getFieldsJsonFile()而得到了NPE,而 ImportJSONSettings bean却没有存在。
ImportJSONSettings bean如何在 FileRetriever 对象中正确创建,以便可以使用?
我尝试将以下内容添加到测试类中,但这无济于事。
@Mock
ImportJSONSettings importJSONSettings;
我需要独立创建它吗?如何将其注入FileRetriever?
任何帮助将不胜感激。
答案 0 :(得分:1)
尝试将@Before
方法上的setup()
批注更改为@BeforeEach
,如下所示:
@BeforeEach
void setup() {
MockitoAnnotations.initMocks(this);
}
这也可能是依赖性问题。确保您拥有io.micrometer:micrometer-core
的最新版本。您可以共享您的测试依赖项吗?
如果您正确设置了上述设置,则无需担心ImportJSONSettings
是否为空,只要您正确设置了getFieldsJsonFile()
即可。