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

前端 未结 7 1535
抹茶落季
抹茶落季 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条回答
  •  余生分开走
    2021-02-12 19:50

    I would leave SpringBoot out of the equation.

    You simply need to test the run method, without going through Spring Boot, since your goal is not to test spring boot, isn't it ? I suppose, the purpose of this test is more for regression, ensuring that your application always throws an IllegalArgumentException when no args are provided? Good old unit test still works to test a single method:

    @RunWith(MockitoJUnitRunner.class)
    public class ApplicationTest {
    
        @InjectMocks
        private Application app = new Application();
    
        @Mock
        private Reader reader;
    
        @Mock
        private Writer writer;
    
        @Test(expected = IllegalArgumentException.class)
        public void testNoArgs() throws Exception {
            app.run();
        }
    
        @Test
        public void testWithArgs() throws Exception {
            List list = new ArrayList();
            list.add("test");
            Mockito.when(reader.get(Mockito.anyString())).thenReturn(list);
    
            app.run("myarg");
    
            Mockito.verify(reader, VerificationModeFactory.times(1)).get(Mockito.anyString());
            Mockito.verify(writer, VerificationModeFactory.times(1)).write(list);
        }
    }
    

    I used Mockito to inject mocks for Reader and Writer:

    
        org.mockito
        mockito-all
        1.9.0
        test
    
    

提交回复
热议问题