Reputation: 1767
I'm using Spring's @Profile
to separate test-related classes from dev and prod. I'm having troubles finding a way to set spring.profiles.active
to test
in pom.xml, for test
goal only. In other words, if the maven goal is test
I want to run this:
mvn test
and still get to classes annotated @Profile("test"),
instead of this:
mvn test -Dspring.profiles.active=test
As it specifies "test"-nature of the run twice.
Is it even possible?
UPDATE: added code
Following two services are for tests and dev/prod. Both implement same interface MyService
MyService for test environment:
@Service
@Profile("test")
@ActiveProfiles("test")
public class TestMyServiceImpl implements MyService {
@Override
public String myMethod(){
...
}
}
MyService for dev environment:
@Service
public class DevMyServiceImpl implements MyService {
@Override
public String myMethod(){
...
}
}
Controller that autowires the MyService:
@RestController
@RequestMapping
public class MyController {
@Autowired
private MyService myService;
@RequestMapping(value = /myendpoint, method = RequestMethod.POST)
public @ResponseBody Response foo(@RequestBody String request) {
Response response = new Response();
response.setResult(myService.myMethod());
return response;
}
}
Test that tests MyController:
@Test
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyControllerTest extends AbstractTestNGSpringContextTests {
@Autowired
private TestRestTemplate restTemplate;
@LocalServerPort
int randomServerPort;
@BeforeSuite
public void config () {
}
@Test
public void testFoo() throws Exception {
final String baseUrl = "http://localhost:" + randomServerPort + "/myendpoint";
URI uri = new URI(baseUrl);
HttpHeaders headers = new HttpHeaders();
HttpEntity request = new HttpEntity<>(headers);
headers.set("X", "true");
ResponseEntity<String> result = this.restTemplate.postForEntity(uri, request, String.class);
}
}
application.properties that is in test/resources directory:
spring.profiles.active=test
Upvotes: 5
Views: 6475
Reputation: 40048
You can use annotation for running test classes with test profile follow the below steps
Step 1: Annotate all the test classes with @Profile("name")
and @ActiveProfiles("name")
Profile
annotation is used to pick up the specified profile ActiveProfiles
is used to activate specified profile for test classesStep 2: Create application.properties
or application.yml
with profile name like application-test.yml and place it inside src/main/resources
or src/test/resources
with test properties
Upvotes: 4