Chr*_*ena 5 java maven spring-boot mockserver
由于防火墙的原因,我们在应用程序中使用的一些 API 无法从本地开发人员计算机访问。
我想使用mockServer来模拟其中一些API,以便我们可以在本地进行开发。
运行测试时,mockServer 可以分别使用 Maven 构建阶段process-test-classes和来启动和停止verify。
当我使用 启动应用程序时如何让它运行mvn spring-boot:run ?
可以覆盖 springboot 上的 beans。因此,您可以根据需要使用 bean 并切换模拟值。下面的示例是覆盖服务并根据您的喜好使用模拟,但您也可以使用接口。
创建服务
@Service
public class ServiceReal {
@Autowired(required = false) // must be required=false. May be disabled by using mock configuration
private JdbcTemplate jdbcTemplate;
public String getInfo() {
return jdbcTemplate...// get a real value from database
}
}
Run Code Online (Sandbox Code Playgroud)
创建模拟服务
@Service
@Primary
@Profile("mocklocal")
public class ServiceMock extend ServiceReal {
@Override
public String getInfo() {
return "Mocked value"
}
}
Run Code Online (Sandbox Code Playgroud)
配置 bean 以稍后在属性上选择其中之一
@Profile("mocklocal")
@PropertySource("classpath:application-mocklocal.properties")
@Configuration
public class ConfigMock {
private static final String PROP_VALUE_TRUE = "true";
private static final boolean PROP_FALSE_DEFAULT_MISSING = false;
private static final String PROP_SERVICE_REAL = "mocklocal.service.real";
private static final String PROP_SERVICE2_REAL = "mocklocal.service2.real";
@Bean
@ConditionalOnProperty( value = PROP_SERVICE_REAL, havingValue = PROP_VALUE_TRUE, matchIfMissing = PROP_FALSE_DEFAULT_MISSING)
public ServiceReal serviceReal(){
return new ServiceMock();
}
@Bean
@ConditionalOnProperty( value = PROP_SERVICE2_REAL, havingValue = PROP_VALUE_TRUE, matchIfMissing = PROP_FALSE_DEFAULT_MISSING)
public Service2Real service2Real(){
return new Service2Mock();
}
}
Run Code Online (Sandbox Code Playgroud)
配置您的 application-mocklocal.properties 以使用模拟
# using ConfigMock
spring.profiles.active=mocklocal
# settig spring to override service and use mock
spring.main.allow-bean-definition-overriding=true
# disable some configuration not required in mocks. you can adjust for amqp, database or other configuration
spring.autoconfigure.exclude[0]=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
spring.autoconfigure.exclude[1]=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
spring.autoconfigure.exclude[2]=org.springframework.boot.autoconfigure.orm.jpa.DataSourceTransactionManagerAutoConfiguration
# enable your service to use mocks not real services
mocklocal.service.real=true
mocklocal.service2.real=true
Run Code Online (Sandbox Code Playgroud)
因此,如果您使用 --spring.profiles.active=mocklocal 启动应用程序,您将获得模拟值
你也可以在测试中使用
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
@SpringBootTest
@TestPropertySource(locations = "classpath:application-mocklocal.properties")
public class RunIntegrationTests {
@Autowired
private MockMvc mockMvc;
@Test
public void run() throws Exception{
...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2940 次 |
| 最近记录: |