首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将程序参数传递给spring引导

将程序参数传递给spring引导
EN

Stack Overflow用户
提问于 2018-12-11 17:54:25
回答 1查看 1.2K关注 0票数 1

我有一个spring引导批处理应用程序,它使用程序参数获取一些文件并对其进行操作。这个应用程序运行良好,但我在运行junit测试时遇到了问题。这是我的代码:

代码语言:javascript
复制
 @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构建完整的路径:

代码语言:javascript
复制
@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
    }
}

使用以下命令,应用程序可以正常工作:

代码语言:javascript
复制
java -jar myApp.jar fileName.txt

是否有任何解决方案将相同的参数传递给junit测试?

我试图使用模拟,但我也有同样的问题:

代码语言:javascript
复制
@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() {
    }
}

以下是错误:

代码语言:javascript
复制
Invocation of init method failed; nested exception is java.lang.NullPointerException
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-12 12:44:51

问题在于InitPaths中的方法before已经在测试中运行了早期的before。这意味着您被嘲笑的ApplicationArguments没有任何被嘲弄的行为。从我的角度来看,您可以使用预定义的行为创建新的模拟ApplicationArguments

代码语言:javascript
复制
@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;
    }
 }
}

我刚检查了一下我的工作。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53729761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档