Vic*_*c K 5 java spring maven spring-boot
我使用 Spring 将@Profile与测试相关的类与开发和产品分开。我在寻找一种在 pom.xml 中设置spring.profiles.activeto的方法时遇到了麻烦,仅出于目标。换句话说,如果 Maven 目标是我想运行这个:testtesttest
mvn test
Run Code Online (Sandbox Code Playgroud)
仍然可以访问带有 @Profile("test") 注释的类,
而不是这样:
mvn test -Dspring.profiles.active=test
Run Code Online (Sandbox Code Playgroud)
因为它指定了运行两次的“测试”性质。
有可能吗?
更新:添加代码
以下两项服务用于测试和开发/生产。两者都实现相同的接口 MyService
MyService测试环境:
@Service
@Profile("test")
@ActiveProfiles("test")
public class TestMyServiceImpl implements MyService {
@Override
public String myMethod(){
...
}
}
Run Code Online (Sandbox Code Playgroud)
MyService 开发环境:
@Service
public class DevMyServiceImpl implements MyService {
@Override
public String myMethod(){
...
}
}
Run Code Online (Sandbox Code Playgroud)
自动装配 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;
}
}
Run Code Online (Sandbox Code Playgroud)
测试 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);
}
}
Run Code Online (Sandbox Code Playgroud)
test/resources 目录中的 application.properties :
spring.profiles.active=test
Run Code Online (Sandbox Code Playgroud)
您可以使用注释通过测试配置文件运行测试类,请按照以下步骤操作
第 1 步:@Profile("name")用和注释所有测试类@ActiveProfiles("name")
Profile注释用于拾取指定的配置文件ActiveProfiles用于激活测试类的指定配置文件第 2 步:创建application.properties或application.yml使用配置文件名称(如application-test.yml)并将其放置在src/main/resources或src/test/resources与测试属性一起放置
| 归档时间: |
|
| 查看次数: |
5508 次 |
| 最近记录: |