Java 类org.mockito.internal.stubbing.answers.ThrowsException 实例源码

项目:teasy    文件:FramesTransparentWebDriverTest.java   
@Test(enabled = false)
public void testFindElementsWhenThereAreDetachedFrames2() {
    final List<WebElement> firstLevelFrames = new ArrayList<WebElement>();
    final List<WebElement> secondLevelFrames = new ArrayList<WebElement>();
    final List<WebElement> thirdLevelFrames = new ArrayList<WebElement>();
    final List<WebElement> lastLevelFrames = emptyList();

    firstLevelFrames.add(mock(WebElement.class));

    final WebElement unstableFrame = mock(WebElement.class);
    when(unstableFrame.getTagName())
            .thenReturn("iframe")
            .thenAnswer(new ThrowsException(new StaleElementReferenceException("stolen")));
    secondLevelFrames.add(unstableFrame);

    thirdLevelFrames.add(mock(WebElement.class));

    when(wrappedDriver.findElements(By.tagName("iframe")))
            .thenReturn(firstLevelFrames)
            .thenReturn(secondLevelFrames)
            .thenReturn(thirdLevelFrames)
            .thenReturn(lastLevelFrames);


    assertThat(driver.findElements(By.cssSelector("selector")), hasSize(0));
}
项目:disq    文件:LenientTest.java   
@Test
public void onExceptionOnTheFirstTime() throws Exception {
    DiskRawQueue queue = mock(DiskRawQueue.class);
    Lenient.Op op = mock(Lenient.Op.class);

    Lenient lenient = new Lenient(queue);

    InOrder orderly = inOrder(queue, op);

    when(op.call())
            .thenAnswer(new ThrowsException(new Error("abc")))
            .thenAnswer(new Returns(42L));

    assertThat(lenient.perform(op)).isEqualTo(42);

    orderly.verify(op).call();
    orderly.verify(queue).reopen();
}
项目:astor    文件:MockitoStubberTest.java   
@Test
public void shouldGetResultsForMethods() throws Throwable {
    invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(simpleMethod));
    invocationContainerImpl.addAnswer(new Returns("simpleMethod"));

    Invocation differentMethod = new InvocationBuilder().differentMethod().toInvocation();
    invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(differentMethod));
    invocationContainerImpl.addAnswer(new ThrowsException(new MyException()));

    assertEquals("simpleMethod", invocationContainerImpl.answerTo(simpleMethod));

    try {
        invocationContainerImpl.answerTo(differentMethod);
        fail();
    } catch (MyException e) {}
}
项目:astor    文件:InvocationContainerImplStubbingTest.java   
@Test
public void should_get_results_for_methods() throws Throwable {
    invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(simpleMethod));
    invocationContainerImpl.addAnswer(new Returns("simpleMethod"));

    Invocation differentMethod = new InvocationBuilder().differentMethod().toInvocation();
    invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(differentMethod));
    invocationContainerImpl.addAnswer(new ThrowsException(new MyException()));

    assertEquals("simpleMethod", invocationContainerImpl.answerTo(simpleMethod));

    try {
        invocationContainerImpl.answerTo(differentMethod);
        fail();
    } catch (MyException e) {}
}
项目:astor    文件:InvocationContainerImplStubbingTest.java   
@Test
public void should_get_results_for_methods_stub_only() throws Throwable {
    invocationContainerImplStubOnly.setInvocationForPotentialStubbing(new InvocationMatcher(simpleMethod));
    invocationContainerImplStubOnly.addAnswer(new Returns("simpleMethod"));

    Invocation differentMethod = new InvocationBuilder().differentMethod().toInvocation();
    invocationContainerImplStubOnly.setInvocationForPotentialStubbing(new InvocationMatcher(differentMethod));
    invocationContainerImplStubOnly.addAnswer(new ThrowsException(new MyException()));

    assertEquals("simpleMethod", invocationContainerImplStubOnly.answerTo(simpleMethod));

    try {
        invocationContainerImplStubOnly.answerTo(differentMethod);
        fail();
    } catch (MyException e) {}
}
项目:teasy    文件:FramesTransparentWebDriverTest.java   
@Test(enabled = false)
public void testFindElementsWhenThereAreDetachedFrames() {
    frames.add(mock(WebElement.class));
    frames.add(mock(WebElement.class, new ThrowsException(new StaleElementReferenceException("stolen"))));

    assertThat(driver.findElements(By.cssSelector("selector")), hasSize(0));
}
项目:hadoop-oss    文件:TestFailoverController.java   
@Test
public void testFailoverFromNonExistantServiceWithFencer() throws Exception {
  DummyHAService svc1 = spy(new DummyHAService(null, svc1Addr));
  // Getting a proxy to a dead server will throw IOException on call,
  // not on creation of the proxy.
  HAServiceProtocol errorThrowingProxy = Mockito.mock(HAServiceProtocol.class,
      Mockito.withSettings()
        .defaultAnswer(new ThrowsException(
            new IOException("Could not connect to host")))
        .extraInterfaces(Closeable.class));
  Mockito.doNothing().when((Closeable)errorThrowingProxy).close();

  Mockito.doReturn(errorThrowingProxy).when(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.anyInt());
  DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr);
  svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());

  try {
    doFailover(svc1, svc2, false, false);
  } catch (FailoverFailedException ffe) {
    fail("Non-existant active prevented failover");
  }
  // Verify that the proxy created to try to make it go to standby
  // gracefully used the right rpc timeout
  Mockito.verify(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.eq(
        CommonConfigurationKeys.HA_FC_GRACEFUL_FENCE_TIMEOUT_DEFAULT));

  // Don't check svc1 because we can't reach it, but that's OK, it's been fenced.
  assertEquals(HAServiceState.ACTIVE, svc2.state);
}
项目:hadoop    文件:TestFailoverController.java   
@Test
public void testFailoverFromNonExistantServiceWithFencer() throws Exception {
  DummyHAService svc1 = spy(new DummyHAService(null, svc1Addr));
  // Getting a proxy to a dead server will throw IOException on call,
  // not on creation of the proxy.
  HAServiceProtocol errorThrowingProxy = Mockito.mock(HAServiceProtocol.class,
      Mockito.withSettings()
        .defaultAnswer(new ThrowsException(
            new IOException("Could not connect to host")))
        .extraInterfaces(Closeable.class));
  Mockito.doNothing().when((Closeable)errorThrowingProxy).close();

  Mockito.doReturn(errorThrowingProxy).when(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.anyInt());
  DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr);
  svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());

  try {
    doFailover(svc1, svc2, false, false);
  } catch (FailoverFailedException ffe) {
    fail("Non-existant active prevented failover");
  }
  // Verify that the proxy created to try to make it go to standby
  // gracefully used the right rpc timeout
  Mockito.verify(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.eq(
        CommonConfigurationKeys.HA_FC_GRACEFUL_FENCE_TIMEOUT_DEFAULT));

  // Don't check svc1 because we can't reach it, but that's OK, it's been fenced.
  assertEquals(HAServiceState.ACTIVE, svc2.state);
}
项目:aliyun-oss-hadoop-fs    文件:TestFailoverController.java   
@Test
public void testFailoverFromNonExistantServiceWithFencer() throws Exception {
  DummyHAService svc1 = spy(new DummyHAService(null, svc1Addr));
  // Getting a proxy to a dead server will throw IOException on call,
  // not on creation of the proxy.
  HAServiceProtocol errorThrowingProxy = Mockito.mock(HAServiceProtocol.class,
      Mockito.withSettings()
        .defaultAnswer(new ThrowsException(
            new IOException("Could not connect to host")))
        .extraInterfaces(Closeable.class));
  Mockito.doNothing().when((Closeable)errorThrowingProxy).close();

  Mockito.doReturn(errorThrowingProxy).when(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.anyInt());
  DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr);
  svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());

  try {
    doFailover(svc1, svc2, false, false);
  } catch (FailoverFailedException ffe) {
    fail("Non-existant active prevented failover");
  }
  // Verify that the proxy created to try to make it go to standby
  // gracefully used the right rpc timeout
  Mockito.verify(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.eq(
        CommonConfigurationKeys.HA_FC_GRACEFUL_FENCE_TIMEOUT_DEFAULT));

  // Don't check svc1 because we can't reach it, but that's OK, it's been fenced.
  assertEquals(HAServiceState.ACTIVE, svc2.state);
}
项目:big-c    文件:TestFailoverController.java   
@Test
public void testFailoverFromNonExistantServiceWithFencer() throws Exception {
  DummyHAService svc1 = spy(new DummyHAService(null, svc1Addr));
  // Getting a proxy to a dead server will throw IOException on call,
  // not on creation of the proxy.
  HAServiceProtocol errorThrowingProxy = Mockito.mock(HAServiceProtocol.class,
      Mockito.withSettings()
        .defaultAnswer(new ThrowsException(
            new IOException("Could not connect to host")))
        .extraInterfaces(Closeable.class));
  Mockito.doNothing().when((Closeable)errorThrowingProxy).close();

  Mockito.doReturn(errorThrowingProxy).when(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.anyInt());
  DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr);
  svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());

  try {
    doFailover(svc1, svc2, false, false);
  } catch (FailoverFailedException ffe) {
    fail("Non-existant active prevented failover");
  }
  // Verify that the proxy created to try to make it go to standby
  // gracefully used the right rpc timeout
  Mockito.verify(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.eq(
        CommonConfigurationKeys.HA_FC_GRACEFUL_FENCE_TIMEOUT_DEFAULT));

  // Don't check svc1 because we can't reach it, but that's OK, it's been fenced.
  assertEquals(HAServiceState.ACTIVE, svc2.state);
}
项目:Wiab.pro    文件:OperationUtilTest.java   
public void testExecuteOperationsSetsErrorOnInvalidRequestException() throws Exception {
  String operationId = "op1";
  OperationRequest operation = new OperationRequest("wavelet.create", operationId);

  OperationService service =
      mock(OperationService.class, new ThrowsException(new InvalidRequestException("")));
  when(operationRegistry.getServiceFor(any(OperationType.class))).thenReturn(service);

  OperationUtil.executeOperation(operation, operationRegistry, context, ALEX);

  assertTrue("Expected one response", context.getResponses().size() == 1);
  assertTrue("Expected an error response", context.getResponse(operationId).isError());
}
项目:hadoop-2.6.0-cdh5.4.3    文件:TestFailoverController.java   
@Test
public void testFailoverFromNonExistantServiceWithFencer() throws Exception {
  DummyHAService svc1 = spy(new DummyHAService(null, svc1Addr));
  // Getting a proxy to a dead server will throw IOException on call,
  // not on creation of the proxy.
  HAServiceProtocol errorThrowingProxy = Mockito.mock(HAServiceProtocol.class,
      Mockito.withSettings()
        .defaultAnswer(new ThrowsException(
            new IOException("Could not connect to host")))
        .extraInterfaces(Closeable.class));
  Mockito.doNothing().when((Closeable)errorThrowingProxy).close();

  Mockito.doReturn(errorThrowingProxy).when(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.anyInt());
  DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr);
  svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());

  try {
    doFailover(svc1, svc2, false, false);
  } catch (FailoverFailedException ffe) {
    fail("Non-existant active prevented failover");
  }
  // Verify that the proxy created to try to make it go to standby
  // gracefully used the right rpc timeout
  Mockito.verify(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.eq(
        CommonConfigurationKeys.HA_FC_GRACEFUL_FENCE_TIMEOUT_DEFAULT));

  // Don't check svc1 because we can't reach it, but that's OK, it's been fenced.
  assertEquals(HAServiceState.ACTIVE, svc2.state);
}
项目:hadoop-plus    文件:TestFailoverController.java   
@Test
public void testFailoverFromNonExistantServiceWithFencer() throws Exception {
  DummyHAService svc1 = spy(new DummyHAService(null, svc1Addr));
  // Getting a proxy to a dead server will throw IOException on call,
  // not on creation of the proxy.
  HAServiceProtocol errorThrowingProxy = Mockito.mock(HAServiceProtocol.class,
      Mockito.withSettings()
        .defaultAnswer(new ThrowsException(
            new IOException("Could not connect to host")))
        .extraInterfaces(Closeable.class));
  Mockito.doNothing().when((Closeable)errorThrowingProxy).close();

  Mockito.doReturn(errorThrowingProxy).when(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.anyInt());
  DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr);
  svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());

  try {
    doFailover(svc1, svc2, false, false);
  } catch (FailoverFailedException ffe) {
    fail("Non-existant active prevented failover");
  }
  // Verify that the proxy created to try to make it go to standby
  // gracefully used the right rpc timeout
  Mockito.verify(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.eq(
        CommonConfigurationKeys.HA_FC_GRACEFUL_FENCE_TIMEOUT_DEFAULT));

  // Don't check svc1 because we can't reach it, but that's OK, it's been fenced.
  assertEquals(HAServiceState.ACTIVE, svc2.state);
}
项目:hops    文件:TestFailoverController.java   
@Test
public void testFailoverFromNonExistantServiceWithFencer() throws Exception {
  DummyHAService svc1 = spy(new DummyHAService(null, svc1Addr));
  // Getting a proxy to a dead server will throw IOException on call,
  // not on creation of the proxy.
  HAServiceProtocol errorThrowingProxy = Mockito.mock(HAServiceProtocol.class,
      Mockito.withSettings()
        .defaultAnswer(new ThrowsException(
            new IOException("Could not connect to host")))
        .extraInterfaces(Closeable.class));
  Mockito.doNothing().when((Closeable)errorThrowingProxy).close();

  Mockito.doReturn(errorThrowingProxy).when(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.anyInt());
  DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr);
  svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());

  try {
    doFailover(svc1, svc2, false, false);
  } catch (FailoverFailedException ffe) {
    fail("Non-existant active prevented failover");
  }
  // Verify that the proxy created to try to make it go to standby
  // gracefully used the right rpc timeout
  Mockito.verify(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.eq(
        CommonConfigurationKeys.HA_FC_GRACEFUL_FENCE_TIMEOUT_DEFAULT));

  // Don't check svc1 because we can't reach it, but that's OK, it's been fenced.
  assertEquals(HAServiceState.ACTIVE, svc2.state);
}
项目:hapi-fhir    文件:XmlParserDstu2Test.java   
/**
 * See #308
 */
@Test
public void testDeclaredExtensionsDontProduceWarning() {
    ReportObservation obs = new ReportObservation();
    obs.setReadOnly(true);

    IParser p = ourCtx.newJsonParser();
    p.setParserErrorHandler(mock(IParserErrorHandler.class, new ThrowsException(new IllegalStateException())));

    String encoded = p.encodeResourceToString(obs);
    ourLog.info(encoded);

    obs = p.parseResource(ReportObservation.class, encoded);
    assertEquals(true, obs.getReadOnly().getValue().booleanValue());
}
项目:hapi-fhir    文件:JsonParserDstu2Test.java   
/**
 * See #308
 */
@Test
public void testDeclaredExtensionsDontProduceWarning() {
    ReportObservation obs = new ReportObservation();
    obs.setReadOnly(true);

    IParser p = ourCtx.newJsonParser();
    p.setParserErrorHandler(mock(IParserErrorHandler.class, new ThrowsException(new IllegalStateException())));

    String encoded = p.encodeResourceToString(obs);
    ourLog.info(encoded);

    obs = p.parseResource(ReportObservation.class, encoded);
    assertEquals(true, obs.getReadOnly().getValue().booleanValue());
}
项目:hapi-fhir    文件:JsonParserDstu2Test.java   
@Test
    public void testParseBundleWithCustomObservationType() {
        ReportObservation obs = new ReportObservation();
        obs.setReadOnly(true);

        IParser p = ourCtx.newJsonParser();
//      p.set
        p.setParserErrorHandler(mock(IParserErrorHandler.class, new ThrowsException(new IllegalStateException())));

        String encoded = p.encodeResourceToString(obs);
        ourLog.info(encoded);

        obs = p.parseResource(ReportObservation.class, encoded);
        assertEquals(true, obs.getReadOnly().getValue().booleanValue());
    }
项目:astor    文件:MocksSerializationTest.java   
@Test
public void shouldAllowThrowsExceptionToBeSerializable() throws Exception {
    // given
    Bar mock = mock(Bar.class, new ThrowsException(new RuntimeException()));
    // when-serialize then-deserialize
    serializeAndBack(mock);
}
项目:astor    文件:MocksSerializationTest.java   
@Test
public void shouldAllowMethodDelegation() throws Exception {
    // given
    Bar barMock = mock(Bar.class, withSettings().serializable());
    Foo fooMock = mock(Foo.class);
    when(barMock.doSomething()).thenAnswer(new ThrowsException(new RuntimeException()));

    //when-serialize then-deserialize
    serializeAndBack(barMock);
}
项目:astor    文件:MockitoStubberTest.java   
@Test
public void shouldFinishStubbingWhenWrongThrowableIsSet() throws Exception {
    state.stubbingStarted();
    try {
        invocationContainerImpl.addAnswer(new ThrowsException(new Exception()));
        fail();
    } catch (MockitoException e) {
        state.validateState();
    }
}
项目:astor    文件:MockitoStubberTest.java   
@Test
public void shouldAddThrowableForVoidMethod() throws Throwable {
    invocationContainerImpl.addAnswerForVoidMethod(new ThrowsException(new MyException()));
    invocationContainerImpl.setMethodForStubbing(new InvocationMatcher(simpleMethod));

    try {
        invocationContainerImpl.answerTo(simpleMethod);
        fail();
    } catch (MyException e) {}
}
项目:astor    文件:MockitoStubberTest.java   
@Test
public void shouldValidateThrowableForVoidMethod() throws Throwable {
    invocationContainerImpl.addAnswerForVoidMethod(new ThrowsException(new Exception()));

    try {
        invocationContainerImpl.setMethodForStubbing(new InvocationMatcher(simpleMethod));
        fail();
    } catch (MockitoException e) {}
}
项目:astor    文件:MockitoStubberTest.java   
@Test
public void shouldValidateThrowable() throws Throwable {
    try {
        invocationContainerImpl.addAnswer(new ThrowsException(null));
        fail();
    } catch (MockitoException e) {}
}
项目:astor    文件:MocksSerializationForAnnotationTest.java   
@Test
public void should_allow_throws_exception_to_be_serializable() throws Exception {
    // given
    when(barMock.doSomething()).thenAnswer(new ThrowsException(new RuntimeException()));

    //when-serialize then-deserialize
    serializeAndBack(barMock);
}
项目:astor    文件:MocksSerializationTest.java   
@Test
public void should_allow_throws_exception_to_be_serializable() throws Exception {
    // given
    Bar mock = mock(Bar.class, new ThrowsException(new RuntimeException()));
    // when-serialize then-deserialize
    serializeAndBack(mock);
}
项目:astor    文件:MocksSerializationTest.java   
@Test
public void should_allow_method_delegation() throws Exception {
    // given
    Bar barMock = mock(Bar.class, withSettings().serializable());
    Foo fooMock = mock(Foo.class);
    when(barMock.doSomething()).thenAnswer(new ThrowsException(new RuntimeException()));

    //when-serialize then-deserialize
    serializeAndBack(barMock);
}
项目:astor    文件:InvocationContainerImplStubbingTest.java   
@Test
public void should_finish_stubbing_when_wrong_throwable_is_set() throws Exception {
    state.stubbingStarted();
    try {
        invocationContainerImpl.addAnswer(new ThrowsException(new Exception()));
        fail();
    } catch (MockitoException e) {
        state.validateState();
    }
}
项目:astor    文件:InvocationContainerImplStubbingTest.java   
@Test
public void should_add_throwable_for_void_method() throws Throwable {
    invocationContainerImpl.addAnswerForVoidMethod(new ThrowsException(new MyException()));
    invocationContainerImpl.setMethodForStubbing(new InvocationMatcher(simpleMethod));

    try {
        invocationContainerImpl.answerTo(simpleMethod);
        fail();
    } catch (MyException e) {}
}
项目:astor    文件:InvocationContainerImplStubbingTest.java   
@Test
public void should_validate_throwable_for_void_method() throws Throwable {
    invocationContainerImpl.addAnswerForVoidMethod(new ThrowsException(new Exception()));

    try {
        invocationContainerImpl.setMethodForStubbing(new InvocationMatcher(simpleMethod));
        fail();
    } catch (MockitoException e) {}
}
项目:astor    文件:InvocationContainerImplStubbingTest.java   
@Test
public void should_validate_throwable() throws Throwable {
    try {
        invocationContainerImpl.addAnswer(new ThrowsException(null));
        fail();
    } catch (MockitoException e) {}
}
项目:hadoop-TCP    文件:TestFailoverController.java   
@Test
public void testFailoverFromNonExistantServiceWithFencer() throws Exception {
  DummyHAService svc1 = spy(new DummyHAService(null, svc1Addr));
  // Getting a proxy to a dead server will throw IOException on call,
  // not on creation of the proxy.
  HAServiceProtocol errorThrowingProxy = Mockito.mock(HAServiceProtocol.class,
      Mockito.withSettings()
        .defaultAnswer(new ThrowsException(
            new IOException("Could not connect to host")))
        .extraInterfaces(Closeable.class));
  Mockito.doNothing().when((Closeable)errorThrowingProxy).close();

  Mockito.doReturn(errorThrowingProxy).when(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.anyInt());
  DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr);
  svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());

  try {
    doFailover(svc1, svc2, false, false);
  } catch (FailoverFailedException ffe) {
    fail("Non-existant active prevented failover");
  }
  // Verify that the proxy created to try to make it go to standby
  // gracefully used the right rpc timeout
  Mockito.verify(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.eq(
        CommonConfigurationKeys.HA_FC_GRACEFUL_FENCE_TIMEOUT_DEFAULT));

  // Don't check svc1 because we can't reach it, but that's OK, it's been fenced.
  assertEquals(HAServiceState.ACTIVE, svc2.state);
}
项目:hardfs    文件:TestFailoverController.java   
@Test
public void testFailoverFromNonExistantServiceWithFencer() throws Exception {
  DummyHAService svc1 = spy(new DummyHAService(null, svc1Addr));
  // Getting a proxy to a dead server will throw IOException on call,
  // not on creation of the proxy.
  HAServiceProtocol errorThrowingProxy = Mockito.mock(HAServiceProtocol.class,
      Mockito.withSettings()
        .defaultAnswer(new ThrowsException(
            new IOException("Could not connect to host")))
        .extraInterfaces(Closeable.class));
  Mockito.doNothing().when((Closeable)errorThrowingProxy).close();

  Mockito.doReturn(errorThrowingProxy).when(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.anyInt());
  DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr);
  svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());

  try {
    doFailover(svc1, svc2, false, false);
  } catch (FailoverFailedException ffe) {
    fail("Non-existant active prevented failover");
  }
  // Verify that the proxy created to try to make it go to standby
  // gracefully used the right rpc timeout
  Mockito.verify(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.eq(
        CommonConfigurationKeys.HA_FC_GRACEFUL_FENCE_TIMEOUT_DEFAULT));

  // Don't check svc1 because we can't reach it, but that's OK, it's been fenced.
  assertEquals(HAServiceState.ACTIVE, svc2.state);
}
项目:hadoop-on-lustre2    文件:TestFailoverController.java   
@Test
public void testFailoverFromNonExistantServiceWithFencer() throws Exception {
  DummyHAService svc1 = spy(new DummyHAService(null, svc1Addr));
  // Getting a proxy to a dead server will throw IOException on call,
  // not on creation of the proxy.
  HAServiceProtocol errorThrowingProxy = Mockito.mock(HAServiceProtocol.class,
      Mockito.withSettings()
        .defaultAnswer(new ThrowsException(
            new IOException("Could not connect to host")))
        .extraInterfaces(Closeable.class));
  Mockito.doNothing().when((Closeable)errorThrowingProxy).close();

  Mockito.doReturn(errorThrowingProxy).when(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.anyInt());
  DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr);
  svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());

  try {
    doFailover(svc1, svc2, false, false);
  } catch (FailoverFailedException ffe) {
    fail("Non-existant active prevented failover");
  }
  // Verify that the proxy created to try to make it go to standby
  // gracefully used the right rpc timeout
  Mockito.verify(svc1).getProxy(
      Mockito.<Configuration>any(),
      Mockito.eq(
        CommonConfigurationKeys.HA_FC_GRACEFUL_FENCE_TIMEOUT_DEFAULT));

  // Don't check svc1 because we can't reach it, but that's OK, it's been fenced.
  assertEquals(HAServiceState.ACTIVE, svc2.state);
}
项目:incubator-wave    文件:OperationUtilTest.java   
public void testExecuteOperationsSetsErrorOnInvalidRequestException() throws Exception {
  String operationId = "op1";
  OperationRequest operation = new OperationRequest("wavelet.create", operationId);

  OperationService service =
      mock(OperationService.class, new ThrowsException(new InvalidRequestException("")));
  when(operationRegistry.getServiceFor(any(OperationType.class))).thenReturn(service);

  OperationUtil.executeOperation(operation, operationRegistry, context, ALEX);

  assertTrue("Expected one response", context.getResponses().size() == 1);
  assertTrue("Expected an error response", context.getResponse(operationId).isError());
}
项目:sonar-xml    文件:DetectSchemaParserTest.java   
@Test
public void io_exception() throws Exception {
  Answer<Object> defaultAnswer = new ThrowsException(new IOException("myexception"));
  InputStream inputStream = Mockito.mock(InputStream.class, defaultAnswer);

  thrown.expect(IllegalStateException.class);
  thrown.expectMessage("myexception");
  detectSchemaParser.findDoctype(inputStream);
}
项目:teasy    文件:FrameAwareWebElementTransformerTest.java   
private WebElement givenStolenElement() {
    return mock(WebElement.class, new ThrowsException(new StaleElementReferenceException("stolen")));
}
项目:hadoop    文件:TestDFSClientRetries.java   
/**
 * Verify that client will correctly give up after the specified number
 * of times trying to add a block
 */
@SuppressWarnings({ "serial", "unchecked" })
@Test
public void testNotYetReplicatedErrors() throws IOException
{ 
  final String exceptionMsg = "Nope, not replicated yet...";
  final int maxRetries = 1; // Allow one retry (total of two calls)
  conf.setInt(DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_KEY, maxRetries);

  NamenodeProtocols mockNN = mock(NamenodeProtocols.class);
  Answer<Object> answer = new ThrowsException(new IOException()) {
    int retryCount = 0;

    @Override
    public Object answer(InvocationOnMock invocation) 
                     throws Throwable {
      retryCount++;
      System.out.println("addBlock has been called "  + retryCount + " times");
      if(retryCount > maxRetries + 1) // First call was not a retry
        throw new IOException("Retried too many times: " + retryCount);
      else
        throw new RemoteException(NotReplicatedYetException.class.getName(),
                                  exceptionMsg);
    }
  };
  when(mockNN.addBlock(anyString(), 
                       anyString(),
                       any(ExtendedBlock.class),
                       any(DatanodeInfo[].class),
                       anyLong(), any(String[].class))).thenAnswer(answer);

  Mockito.doReturn(
          new HdfsFileStatus(0, false, 1, 1024, 0, 0, new FsPermission(
              (short) 777), "owner", "group", new byte[0], new byte[0],
              1010, 0, null, (byte) 0)).when(mockNN).getFileInfo(anyString());

  Mockito.doReturn(
          new HdfsFileStatus(0, false, 1, 1024, 0, 0, new FsPermission(
              (short) 777), "owner", "group", new byte[0], new byte[0],
              1010, 0, null, (byte) 0))
      .when(mockNN)
      .create(anyString(), (FsPermission) anyObject(), anyString(),
          (EnumSetWritable<CreateFlag>) anyObject(), anyBoolean(),
          anyShort(), anyLong(), (CryptoProtocolVersion[]) anyObject());

  final DFSClient client = new DFSClient(null, mockNN, conf, null);
  OutputStream os = client.create("testfile", true);
  os.write(20); // write one random byte

  try {
    os.close();
  } catch (Exception e) {
    assertTrue("Retries are not being stopped correctly: " + e.getMessage(),
         e.getMessage().equals(exceptionMsg));
  }
}
项目:aliyun-oss-hadoop-fs    文件:TestDFSClientRetries.java   
/**
 * Verify that client will correctly give up after the specified number
 * of times trying to add a block
 */
@SuppressWarnings({ "serial", "unchecked" })
@Test
public void testNotYetReplicatedErrors() throws IOException
{ 
  final String exceptionMsg = "Nope, not replicated yet...";
  final int maxRetries = 1; // Allow one retry (total of two calls)
  conf.setInt(HdfsClientConfigKeys.BlockWrite.LOCATEFOLLOWINGBLOCK_RETRIES_KEY, maxRetries);

  NamenodeProtocols mockNN = mock(NamenodeProtocols.class);
  Answer<Object> answer = new ThrowsException(new IOException()) {
    int retryCount = 0;

    @Override
    public Object answer(InvocationOnMock invocation) 
                     throws Throwable {
      retryCount++;
      System.out.println("addBlock has been called "  + retryCount + " times");
      if(retryCount > maxRetries + 1) // First call was not a retry
        throw new IOException("Retried too many times: " + retryCount);
      else
        throw new RemoteException(NotReplicatedYetException.class.getName(),
                                  exceptionMsg);
    }
  };
  when(mockNN.addBlock(anyString(), 
                       anyString(),
                       any(ExtendedBlock.class),
                       any(DatanodeInfo[].class),
                       anyLong(), any(String[].class))).thenAnswer(answer);

  Mockito.doReturn(
          new HdfsFileStatus(0, false, 1, 1024, 0, 0, new FsPermission(
              (short) 777), "owner", "group", new byte[0], new byte[0],
              1010, 0, null, (byte) 0, null)).when(mockNN).getFileInfo(anyString());

  Mockito.doReturn(
          new HdfsFileStatus(0, false, 1, 1024, 0, 0, new FsPermission(
              (short) 777), "owner", "group", new byte[0], new byte[0],
              1010, 0, null, (byte) 0, null))
      .when(mockNN)
      .create(anyString(), (FsPermission) anyObject(), anyString(),
          (EnumSetWritable<CreateFlag>) anyObject(), anyBoolean(),
          anyShort(), anyLong(), (CryptoProtocolVersion[]) anyObject());

  final DFSClient client = new DFSClient(null, mockNN, conf, null);
  OutputStream os = client.create("testfile", true);
  os.write(20); // write one random byte

  try {
    os.close();
  } catch (Exception e) {
    assertTrue("Retries are not being stopped correctly: " + e.getMessage(),
         e.getMessage().equals(exceptionMsg));
  }
}
项目:big-c    文件:TestDFSClientRetries.java   
/**
 * Verify that client will correctly give up after the specified number
 * of times trying to add a block
 */
@SuppressWarnings({ "serial", "unchecked" })
@Test
public void testNotYetReplicatedErrors() throws IOException
{ 
  final String exceptionMsg = "Nope, not replicated yet...";
  final int maxRetries = 1; // Allow one retry (total of two calls)
  conf.setInt(DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_KEY, maxRetries);

  NamenodeProtocols mockNN = mock(NamenodeProtocols.class);
  Answer<Object> answer = new ThrowsException(new IOException()) {
    int retryCount = 0;

    @Override
    public Object answer(InvocationOnMock invocation) 
                     throws Throwable {
      retryCount++;
      System.out.println("addBlock has been called "  + retryCount + " times");
      if(retryCount > maxRetries + 1) // First call was not a retry
        throw new IOException("Retried too many times: " + retryCount);
      else
        throw new RemoteException(NotReplicatedYetException.class.getName(),
                                  exceptionMsg);
    }
  };
  when(mockNN.addBlock(anyString(), 
                       anyString(),
                       any(ExtendedBlock.class),
                       any(DatanodeInfo[].class),
                       anyLong(), any(String[].class))).thenAnswer(answer);

  Mockito.doReturn(
          new HdfsFileStatus(0, false, 1, 1024, 0, 0, new FsPermission(
              (short) 777), "owner", "group", new byte[0], new byte[0],
              1010, 0, null, (byte) 0)).when(mockNN).getFileInfo(anyString());

  Mockito.doReturn(
          new HdfsFileStatus(0, false, 1, 1024, 0, 0, new FsPermission(
              (short) 777), "owner", "group", new byte[0], new byte[0],
              1010, 0, null, (byte) 0))
      .when(mockNN)
      .create(anyString(), (FsPermission) anyObject(), anyString(),
          (EnumSetWritable<CreateFlag>) anyObject(), anyBoolean(),
          anyShort(), anyLong(), (CryptoProtocolVersion[]) anyObject());

  final DFSClient client = new DFSClient(null, mockNN, conf, null);
  OutputStream os = client.create("testfile", true);
  os.write(20); // write one random byte

  try {
    os.close();
  } catch (Exception e) {
    assertTrue("Retries are not being stopped correctly: " + e.getMessage(),
         e.getMessage().equals(exceptionMsg));
  }
}
项目:hadoop-2.6.0-cdh5.4.3    文件:TestDFSClientRetries.java   
/**
 * Verify that client will correctly give up after the specified number
 * of times trying to add a block
 */
@SuppressWarnings({ "serial", "unchecked" })
@Test
public void testNotYetReplicatedErrors() throws IOException
{ 
  final String exceptionMsg = "Nope, not replicated yet...";
  final int maxRetries = 1; // Allow one retry (total of two calls)
  conf.setInt(DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_KEY, maxRetries);

  NamenodeProtocols mockNN = mock(NamenodeProtocols.class);
  Answer<Object> answer = new ThrowsException(new IOException()) {
    int retryCount = 0;

    @Override
    public Object answer(InvocationOnMock invocation) 
                     throws Throwable {
      retryCount++;
      System.out.println("addBlock has been called "  + retryCount + " times");
      if(retryCount > maxRetries + 1) // First call was not a retry
        throw new IOException("Retried too many times: " + retryCount);
      else
        throw new RemoteException(NotReplicatedYetException.class.getName(),
                                  exceptionMsg);
    }
  };
  when(mockNN.addBlock(anyString(), 
                       anyString(),
                       any(ExtendedBlock.class),
                       any(DatanodeInfo[].class),
                       anyLong(), any(String[].class))).thenAnswer(answer);

  Mockito.doReturn(
          new HdfsFileStatus(0, false, 1, 1024, 0, 0, new FsPermission(
              (short) 777), "owner", "group", new byte[0], new byte[0],
              1010, 0, null, (byte) 0)).when(mockNN).getFileInfo(anyString());

  Mockito.doReturn(
          new HdfsFileStatus(0, false, 1, 1024, 0, 0, new FsPermission(
              (short) 777), "owner", "group", new byte[0], new byte[0],
              1010, 0, null, (byte) 0))
      .when(mockNN)
      .create(anyString(), (FsPermission) anyObject(), anyString(),
          (EnumSetWritable<CreateFlag>) anyObject(), anyBoolean(),
          anyShort(), anyLong(), (CryptoProtocolVersion[]) anyObject());

  final DFSClient client = new DFSClient(null, mockNN, conf, null);
  OutputStream os = client.create("testfile", true);
  os.write(20); // write one random byte

  try {
    os.close();
  } catch (Exception e) {
    assertTrue("Retries are not being stopped correctly: " + e.getMessage(),
         e.getMessage().equals(exceptionMsg));
  }
}