spring-boot - 将程序参数传递给spring boot
问题描述
我有一个 Spring Boot 批处理应用程序,它使用程序参数来获取一些文件并对其进行操作。该应用程序运行良好,但我在运行 junit 测试时遇到问题。这是我的代码:
@Component
public class ApplicationArguments implements InitializingBean {
@Autowired private org.springframework.boot.ApplicationArguments appArgs;
private String filePath;
@Override
public void afterPropertiesSet() throws Exception {
filePath = appArgs.getSourceArgs()[0];
}
}
这个 bean 被另一个 bean 用来构建完整路径:
@Component
public class InitPaths implements InitializingBean {
@Autowired private ApplicationArguments myAppArgs;
private String fullPath;
@Override
public void afterPropertiesSet() throws Exception {
fullPath = myAppArgs.getFilePath(); //this will be null when launching tests
fullPath.toString();//this will throw a NullPointerException if we run the test
}
}
该应用程序使用此命令可以正常工作:
java -jar myApp.jar fileName.txt
是否有任何解决方案可以将相同的参数传递给 junit 测试?
我尝试使用模拟,但我遇到了同样的问题:
@RunWith(SpringRunner.class)
@SpringBootTest
public class BatchTest {
@MockBean
ApplicationArguments applicationArguments;
@Autowired
@InjectMocks
InitPaths initPaths;
@Before
public void before() {
when(applicationArguments.getFilePath()).thenReturn("myCustomFile.dat");
}
@Test
public void contextLoad() {
}
}
这是错误:
Invocation of init method failed; nested exception is java.lang.NullPointerException
解决方案
问题是因为方法afterPropertiesSet()
inInitPaths
已经before
在测试中运行了较早的它们。这意味着您的嘲笑ApplicationArguments
没有任何嘲笑的行为。ApplicationArguments
从我的角度来看,您可能会使用预定义的行为创建新的模拟
@RunWith(SpringRunner.class)
@SpringBootTest
@Import(ApplicationArgumentsTestConfig.class)
public class BatchTest {
@Autowired
InitPaths initPaths;
@Test
public void contextLoad() {
}
public static class ApplicationArgumentsTestConfig {
@Bean
@Primary
public ApplicationArguments mockArg() {
ApplicationArguments mocked = Mockito.mock(ApplicationArguments.class);
Mockito.when(mocked.getFilePath()).thenReturn("test-mock-path");
return mocked;
}
}
}
我刚刚为我检查了工作。
推荐阅读
- javascript - 使用 Angular 5 发送自定义标头
- r - 计算从 1 列到另一列中的值的总和,然后计算总和
- java - 如何使 TextArea 填充屏幕的中心?
- javascript - 无法使用 React Router Link 组件访问状态值
- three.js - Threejs 纹理贴图到球体错误(three.min.js:120 THREE.WebGLRenderer: image is not power of two (1000x500))
- ios - 缩小到主页过渡动画期间的 iOS 应用程序图标背景颜色
- macos - .htaccess
我正在尝试在我的 Mac 上使用http://crud-admin-generator.com/设置 crud 应用程序所以我按照上面链接中的步骤来生成所有实体。在运行服务器时,我需要在我的 mac 上设置 .htac
- c# - C# - WPF - 改变我的窗口的继承
- ruby-on-rails - docker 中的 Capybara 无头 chrome 返回 DevToolsActivePort 文件不存在
- clang - 未定义符号:__asan_option_detect_stack_use_after_return