package dk.thoerup.circuitbreaker; import org.junit.*; import static org.junit.Assert.*; import dk.thoerup.curcuitbreaker.*; import java.io.IOException; public class TestCircuitBreaker { class SucceedingInvocation implements CircuitInvocation { public Object proceed() throws Exception { return "OK"; } } class FailingInvocation implements CircuitInvocation { public Object proceed() throws Exception { throw new IOException("Error"); } } CircuitBreaker cb; @Before public void setup() { cb = new CircuitBreaker("test",2,500); } @Test public void simpleTest() throws Throwable { String retval = (String) cb.invoke( new SucceedingInvocation() ); assertEquals(retval, "OK"); assertTrue(cb.getFailureCount() == 0); } @Test(expected=IOException.class) public void simpleFailingTest() throws Throwable { cb.invoke( new FailingInvocation() ); } @Test public void failingTest() { try { cb.invoke( new FailingInvocation() ); }catch (Throwable t) {} assertTrue(cb.getFailureCount() == 1); } @Test public void failAndResetTest() throws Throwable { try { cb.invoke( new FailingInvocation() ); }catch (Throwable t) {} cb.invoke(new SucceedingInvocation() ); //after one good it should reset back to closed assertTrue(cb.isClosed()); assertTrue(cb.getFailureCount() == 0); } @Test public void normalOpenTest() throws Throwable { try{ cb.invoke( new FailingInvocation() ); } catch (IOException e) {} try{ cb.invoke( new FailingInvocation() ); } catch (IOException e) {} assertTrue( cb.isOpen() ); } @Test public void forcedResetTest() throws Throwable { try{ cb.invoke( new FailingInvocation() ); } catch (IOException e) {} try{ cb.invoke( new FailingInvocation() ); } catch (IOException e) {} cb.reset(); assertTrue( cb.isClosed() ); } }