Springboot and maven: how to launch unit tests automatically with two profiles

匆匆过客 提交于 2019-12-25 01:09:41

问题


This question is the continuation of question "SpringBoot: how to run tests twice, with two different config files".

I use to compile my project using mvn clean install. Doing that, maven also launches my unit tests and I immediately knows whether my development is correct.

I am actually working on a module that embeds a JMS connection. my module supports two JMS buses: EMS and AMQ. The bus to be used is specified in the configuration of my module

As a consequence, I need to create two profiles, one for EMS and one for AMQ.

However, when I launch my mvn clean install I want that maven launches automatically the tests using the two profiles, not only one; I don't want to have to launch it twice: mvn clean test -Dspring.profiles.active=ems ; mvn clean test -Dspring.profiles.active=amq

Thank you for help


回答1:


You can pass the two profiles separated by a comma:

mvn clean install -Dspring.profiles.active=ems,amq

And then you'll have two active profiles:

The following profiles are active: ems,amq




回答2:


You can also specify in the src/test/resources/application.properties specific properties that apply every time Spring tests are run. Seems cleaner to me than specifying them on Maven command line. For your case :

spring.profiles.active=ems,amq



回答3:


I think that there is a miss-understanding; It seems that when I run my tests with spring.profiles.active=ems,amq:

  • all tests are launched one time
  • both profiles are enabled

What I want is different:

  • launch all tests TWO TIMES
  • first time with ems (and only ems) profile enabled
  • second time with amq (and only amq) profile enabled

For the moment, I do not succeed to find a solution; evey clue is welcome

Regards




回答4:


I found a solution for my issue; a kind of trick based on:

  • overloading the SpringJUnit4ClassRunner
  • redefining the run() method in order to:

    1. call force the use of the first profile
    2. call the origial run() method
    3. do the same with the other profile

public class MultiProfileTestRunner extends SpringJUnit4ClassRunner {
...


public void run(RunNotifier notifier) {
    System.setProperty("spring.profiles.active", "ems");
    super.run(notifier);

    System.setProperty("spring.profiles.active", "amq");
    super.run(notifier);
}

Between both calls to super.run() we have to 'force' Spring to reload its context, otherwize the profile change is not taken into account

I did it by using the annotation @DirtiesContext(classMode = AFTER_CLASS) on my tests



来源:https://stackoverflow.com/questions/57340378/springboot-and-maven-how-to-launch-unit-tests-automatically-with-two-profiles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!