Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass program arguments in a @SpringBootTest?

I'm building a spring boot application. I want to run it like this:

 java -jar myjar.jar inputFile outputFile

How do I write a @SpringBootTest for this? I imagine that using @SpringBootTest would make Spring fail during startup because some of my code would say, "you need to provide an inputFile and outputFile". Is there a way to pass program arguments when using a @SpringBootTest?

I'm inferring from this answer that I may have to use a SpringApplicationBuilder to do this.

I thought I had the answer but I was wrong. This incorrect information may still be useful to some:


(This information is wrong. I think that some arguments can't be referred to in code as properties, but not all. I still don't know how to get the application arguments in a @SpringBootTest) I was confused because I didn't understand the terminology. The annotation has a parameter for "properties". I thought it was to point it at a property file, but the documentation says:

Properties in form key=value that should be added to the Spring Environment before the test runs.

The other piece of the terminology puzzle is that what I called "program arguments" the Spring docs refer to as "properties".

This is some additional relevant documentation: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-application-arguments


This is a workaround (not an answer). You can do something like this:

private SpringApplicationBuilder subject;

@Before
public void setUp() throws Exception {
    subject = new SpringApplicationBuilder(Application.class);
}

@Test
public void requiresInputAndOutput() throws Exception {

    thrown.expect(IllegalStateException.class);
    subject.run();
}

@Test
public void happyPathHasNoErrors() throws Exception {

    subject.run(EXISTING_INPUT_FILE, "does_not_exist");
}

I don't like this very much. It prevents me from using @Autowired elsewhere in my test.

like image 875
Daniel Kaplan Avatar asked May 11 '26 23:05

Daniel Kaplan


1 Answers

if your program arguments is

--arg1=val1

before springboot version 2.2.0 you can use

@SpringBootTest({"arg1=val1"})

after springboot 2.2.0 you can use

@SpringBootTest(args={"--arg1=val1"})
like image 131
ryanlee Avatar answered May 14 '26 13:05

ryanlee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!