将程序参数传递给Spring Boot

时间:2018-12-11 17:54:25

标签: spring-boot spring-test

我有一个spring boot batch应用程序,它使用程序参数来获取一些文件并对其进行操作。该应用程序工作正常,但运行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被另一人用来构建完整路径:

@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

1 个答案:

答案 0 :(得分:0)

问题是因为afterPropertiesSet()中的方法InitPaths在测试中运行了早于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;
    }
 }
}

我刚刚为我工作。