1 package net.secodo.jcircuitbreaker.breakhandler;
2
3 import net.secodo.jcircuitbreaker.breaker.CircuitBreaker;
4 import net.secodo.jcircuitbreaker.breaker.ContextAwareCircuitBreaker;
5 import net.secodo.jcircuitbreaker.breaker.execution.ExecutionContext;
6 import net.secodo.jcircuitbreaker.breakhandler.exception.BreakHandlerException;
7 import net.secodo.jcircuitbreaker.breakhandler.impl.ReturnStaticValueHandler;
8 import net.secodo.jcircuitbreaker.breakstrategy.BreakStrategy;
9 import net.secodo.jcircuitbreaker.task.Task;
10 import org.junit.Test;
11 import java.util.concurrent.Callable;
12 import java.util.concurrent.atomic.AtomicInteger;
13 import static org.hamcrest.CoreMatchers.equalTo;
14 import static org.junit.Assert.assertThat;
15 import static org.junit.Assert.fail;
16 import static org.mockito.Mockito.mock;
17
18
19 public class BreakHandlerFactoryTest {
20 @Test
21 public void shouldThrowBreakHandlerExceptionInCaseMakeHandlerMethodReturnedNull() throws Exception {
22
23 final BreakHandler<Byte> myBreakHandlerFactory = (BreakHandlerFactory<Byte>) (task, executionContext) -> null;
24
25
26 try {
27 myBreakHandlerFactory.onBreak(mock(ContextAwareCircuitBreaker.class),
28 mock(Task.class),
29 mock(BreakStrategy.class),
30 mock(ExecutionContext.class));
31
32 fail(BreakHandlerException.class.getSimpleName() + " should have been thrown when makeHandler returns null");
33 } catch (BreakHandlerException e) {
34
35 }
36
37
38
39 }
40
41 @Test
42 public void shouldReturnNewInstanceOfHandlerWhenMakeHandlerMethodReturnsNewInstance() throws Exception {
43
44 AtomicInteger callsCounter = new AtomicInteger();
45
46
47 final BreakHandler<Byte> myBreakHandlerFactory = (BreakHandlerFactory<Byte>) (task, executionContext) -> {
48
49 callsCounter.incrementAndGet();
50 return new ReturnStaticValueHandler<>((byte) callsCounter.intValue());
51 };
52
53
54 final Byte value1 = myBreakHandlerFactory.onBreak(mock(ContextAwareCircuitBreaker.class),
55 mock(Task.class),
56 mock(BreakStrategy.class),
57 mock(ExecutionContext.class));
58
59 final Byte value2 = myBreakHandlerFactory.onBreak(mock(ContextAwareCircuitBreaker.class),
60 mock(Task.class),
61 mock(BreakStrategy.class),
62 mock(ExecutionContext.class));
63
64
65
66 assertThat(value1, equalTo((byte) 1));
67 assertThat(value2, equalTo((byte) 2));
68 }
69
70 }