how to run/turn off selective tests based on profi

2019-04-27 01:09发布

I have a spring-boot application for which I am writing IT tests.

The data for the tests comes from application-dev.properties when I activate dev profile

Here is what I have for tests:

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class ApplicationTests {

    @Autowired
    Environment env;

    @Test
    public void contextLoads() {
        System.out.println(Arrays.toString((env.getActiveProfiles())));

    }

}

ServiceITTest

public class ServiceITTest extends ApplicationTests {


     @value
     String username;

     @value
     String address;

     @Autowired
     MyService myService;


      @Test
      public void check_for_valid_username_address(){
            myService.validate(username,address);
      }
}

I want the above test to run only when I set the profile of "dev","qa". by default, it should not run.

Is it possible to get that fine control in spring boot testing?

2条回答
走好不送
2楼-- · 2019-04-27 01:51

I wanted to exclude tests that required an external service but I couldn't get that to work the way I wanted (more or less a non-existent @IfNotProfileValue).

As an alternative, I used the JUnit Assume.assumeThat which provided the behavior I wanted. e.g.,

Assume.assumeThat("Skipping Test: No username property", this.username, not(isEmptyString()));

I ended up not using a profile to drive it but you should be able to define a property or use the Environment to determine if a profile is active.

The assumeThat can be used in @Test and @Before methods but be aware that the @After methods will still run so cleanup might need a code guard.

查看更多
做自己的国王
3楼-- · 2019-04-27 02:02

You would want to use the @IfProfileValue annotation. Unfortunately it doesn't work directly on the active profiles but it can read a property so if you only define a specific property within the profiles that you want to run the test on then you can use that annotation on that specific property.

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#integration-testing-annotations-junit

查看更多
登录 后发表回答