在运行“ MVN测试”时设置“测试”配置文件

问题描述 投票:1回答:1

我正在使用Spring的@Profile将与测试相关的类与dev和prod分开。我很难找到一种方法来将pom.xml中的spring.profiles.active设置为test,仅用于test目标。换句话说,如果行家目标是test,我要运行此代码:

mvn test

并且仍然可以看到带有@Profile(“ test”)注释的类,代替这个:

mvn test -Dspring.profiles.active=test 

因为它指定两次运行的“测试”性质。

甚至有可能吗?

UPDATE:添加的代码

以下两项服务分别用于测试和开发/生产。两者都实现相同的接口MyService

用于测试环境的MyService:

@Service
@Profile("test")
@ActiveProfiles("test")
public class TestMyServiceImpl implements MyService {
    @Override
  public String myMethod(){
    ...
    }
}

用于开发环境的MyService:

@Service
public class DevMyServiceImpl implements MyService {
    @Override
  public String myMethod(){
    ...
    }
}

自动连接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;
  }
}

测试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);
  }
}

test / resources目录中的application.properties:

spring.profiles.active=test
java spring maven spring-boot
1个回答
2
投票

您可以使用批注通过测试配置文件运行测试类,请执行以下步骤

步骤1:@Profile("name")@ActiveProfiles("name")]注释所有测试类

  • Profile批注用于拾取指定的配置文件
  • ActiveProfiles用于激活测试类的指定配置文件
  • 步骤2:

使用配置文件名称创建application.propertiesapplication.yml并将其放置在具有测试属性的src/main/resourcessrc/test/resources
© www.soinside.com 2019 - 2024. All rights reserved.