英文:
How to unit test a Service using Circuit Breaker without activating the Circuit Breaker
问题
我在我的服务类中添加了一个断路器(Circuit Breaker),但我注意到之后所有的单元测试都失败了。
- 有没有一种好的方法来测试实现了**断路器(Circuit Breaker)**的服务,而不会破坏之前的单元测试?
- 有没有一种方法可以在运行测试时模拟**断路器(Circuit Breaker)**或禁用它?
- **断路器(Circuit Breaker)**应该只在集成测试中进行测试吗?
以下是我的代码:
public class PersonService {
private final CircuitBreakerFactory circuitBreakerFactory;
public PersonService(CircuitBreakerFactory circuitBreakerFactory) {
this.circuitBreakerFactory = circuitBreakerFactory;
}
public List<Item> getPersonItems() {
return circuitBreakerConfiguration.create("CB_Service").run(() -> apiCall.getItems(), exception -> {
log.error("An error occurs");
throw new ItemServiceException("No Item available");
});
}
}
英文:
I add a Circuit Breaker in my service class, but I noticed all my unit tests are failing after that.
- Is there a good way to test a service implementing a Circuit Breaker without breaking previous unit tests
- Is there a way to mock the Circuit Breaker or disable it while running my tests
- Should Circuit Breaker should be test only in integration tests.
Here is my code:
public class PersonService {
private final CircuitBreakerFactory circuitBreakerFactory;
public PersonService(CircuitBreakerFactory circuitBreakerFactory) {
this.circuitBreakerFactory = circuitBreakerFactory;
}
public List<Item> getPersonItems() {
return circuitBreakerConfiguration.create("CB_Service").run(() -> apiCall.getItems(), exception -> {
log.error("An error occurs");
throw new ItemServiceException("No Item available");
});
}
}
答案1
得分: 1
你可能需要在测试中触发断路器后进行复位,特别是在你知道计数器正在增加的情况下。
我们使用resilience4j,它有一个reset()
方法,详见 - https://resilience4j.readme.io/docs/examples#reset-circuitbreaker。
我们将其用于@AfterEach
测试中,CircuitBreakerUtil只是CircuitBreakerRegistry的包装器。
@AfterEach
public void stopCircuitBreakerTripping() {
CircuitBreakerUtil.get("Breaker").reset();
}
<details>
<summary>英文:</summary>
You should probably reset the circuit breaker after tripping it in tests you know are incrementing the counter
We use resilience4j and it has a `reset()` method see - https://resilience4j.readme.io/docs/examples#reset-circuitbreaker.
We use it in the `@AfterEach` for tests CircuitBreakerUtil is just a wrapper for the [CircuitBreakerRegistry][1].
@AfterEach
public void stopCircuitBreakerTripping() {
CircuitBreakerUtil.get("Breaker").reset();
}
[1]: https://resilience4j.readme.io/docs/examples#override-the-registrystore
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论