Using junit test to pass command line argument to Spring Boot application

前端 未结 7 1537
抹茶落季
抹茶落季 2021-02-12 19:07

I have a very basic Spring Boot application, which is expecting an argument from command line, and without it doesn\'t work. Here is the code.

@SpringBootApplica         


        
7条回答
  •  闹比i
    闹比i (楼主)
    2021-02-12 19:58

    I´ve managed to find a way to create Junit tests that worked fine with SpringBoot by injecting the ApplicationContext in my test and calling a CommandLineRunner with the required parameters.

    The final code looks like that:

    package my.package.
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.context.ApplicationContext;
    import org.springframework.test.context.junit4.SpringRunner;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    class AsgardBpmClientApplicationIT {
    
        @Autowired
        ApplicationContext ctx;
    
        @Test
        public void testRun() {
            CommandLineRunner runner = ctx.getBean(CommandLineRunner.class);
            runner.run ( "-k", "arg1", "-i", "arg2");
        }
    
    }
    

提交回复
热议问题