How to test main class of Spring-boot application

后端 未结 9 1878
心在旅途
心在旅途 2020-12-03 00:18

I have a spring-boot application where my @SpringBootApplication starter class looks like a standard one. So I created many tests for all my functi

9条回答
  •  情话喂你
    2020-12-03 00:55

    Even though this question has been answered extensively I had a use case that is not covered here that is perhaps interesting to share. I am validating some properties at startup and I wanted to assert that the application would fail to start if these properties were configured wrong. In JUnit4 I could have done something like this:

    @ActiveProfiles("incorrect")
    @SpringBoot
    public class NetworkProbeApplicationTest {
    
        @Test(expected=ConfigurationPropertiesBindException.class)
        public void contextShouldNotLoadWhenPropertiesIncorrect() {
        }
    }
    

    But in JUnit5 you can no longer add the "expected" value to your @Test annotation and you have to do it differently. And since I wanted to start the application with an incorrect set of properties I needed to pass in which profile to use as a main() argument. I could not really find this documented anywhere, but passing in arguments through the main() method requires you to prefix your arguments with a double hyphen and separate the key and value with an equals sign. A complete test would look like this:

    import org.junit.jupiter.api.Test;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.context.properties.ConfigurationPropertiesBindException;
    
    import static org.junit.jupiter.api.Assertions.assertThrows;
    import static org.junit.jupiter.api.Assertions.assertTrue;
    
    public class NetworkProbeApplicationTest {
    
        @Test
        public void contextShouldNotLoadWhenPropertiesIncorrect() {
            Exception exception = assertThrows(ConfigurationPropertiesBindException.class, () -> {
                SpringApplication.run(NetworkProbeApplication.class, "--spring.profiles.active=incorrect");
            });
    
            String expectedMessage = "Error creating bean with name 'dnsConfiguration': Could not bind properties to 'DnsConfiguration' : prefix=dns";
    
            assertTrue(exception.getMessage().contains(expectedMessage));
        }
    }
    

提交回复
热议问题