Java 类org.junit.rules.ExpectedException 实例源码

项目:metal    文件:ErrorsTest.java   
@Test
public void noValueForSize() throws IOException {
    thrown = ExpectedException.none();
    // Basic division by zero.
    final Token token = def("a", div(con(1), con(0)));
    assertFalse(token.parse(env(stream(1))).isPresent());
    // Try to negate division by zero.
    final Token token2 = def("a", neg(div(con(1), con(0))));
    assertFalse(token2.parse(env(stream(1))).isPresent());
    // Add one to division by zero.
    final Token token3 = def("a", add(div(con(1), con(0)), con(1)));
    assertFalse(token3.parse(env(stream(1))).isPresent());
    // Add division by zero to one.
    final Token token4 = def("a", add(con(1), div(con(1), con(0))));
    assertFalse(token4.parse(env(stream(1))).isPresent());
}
项目:hbase    文件:TestThriftHttpServer.java   
@Test
public void testExceptionThrownWhenMisConfigured() throws Exception {
  Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
  conf.set("hbase.thrift.security.qop", "privacy");
  conf.setBoolean("hbase.thrift.ssl.enabled", false);

  ThriftServerRunner runner = null;
  ExpectedException thrown = ExpectedException.none();
  try {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("Thrift HTTP Server's QoP is privacy, " +
        "but hbase.thrift.ssl.enabled is false");
    runner = new ThriftServerRunner(conf);
    fail("Thrift HTTP Server starts up even with wrong security configurations.");
  } catch (Exception e) {
  }

  assertNull(runner);
}
项目:yauaa    文件:TestAnnotationSystem.java   
@Test
public void testAnnotationBasedParser() {
    expectedEx = ExpectedException.none();

    MyMapper mapper = new MyMapper();

    TestRecord record = new TestRecord("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
        "Chrome/48.0.2564.82 Safari/537.36");

    record = mapper.enrich(record);

    assertEquals("Desktop", record.deviceClass);
    assertEquals("Chrome 48.0.2564.82", record.agentNameVersion);
}
项目:easy-mybatis    文件:MybatisDaoTest.java   
@After
public void tearDown() throws Exception {
    //单个测试案例执行完之后,引用置空,防止数据污染
    tEmployee = null;
    tEmployeeExample = null;
    expectedException = ExpectedException.none();
}
项目:derrick    文件:UrlHelperTest.java   
@Test
public void testMakeFromUrlAndPath() throws Exception {
    if (expectedResult == null) {
        expectedException.expect(IllegalArgumentException.class);
    } else {
        expectedException = ExpectedException.none();
    }

    assertThat(UrlHelper.makeFromUrlAndPath(url, path)).isEqualTo(expectedResult);
}
项目:Mockery    文件:BrewJavaFile.java   
private TypeSpec classTest(ClassName className, List<MethodSpec> methodSpecs) {
  String methodName = Introspector
      .decapitalize(className.simpleName());

  MethodSpec abstractMethodInstanceToTest = methodBuilder(methodName)
      .addModifiers(Modifier.ABSTRACT, Modifier.PROTECTED)
      .returns(className)
      .build();

  FieldSpec exception = FieldSpec.builder(ExpectedException.class, "exception")
      .addAnnotation(Rule.class)
      .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
      .initializer("$T.none()", ExpectedException.class)
      .build();

  return TypeSpec.classBuilder(className.simpleName() + "Test_")
      .addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC)
      .addMethod(abstractMethodInstanceToTest)
      .addField(exception)
      .addAnnotation(AnnotationSpec.builder(Generated.class)
          .addMember("value", "$S", MockeryProcessor.class.getCanonicalName())
          .addMember("comments", "$S", CMessages.codeGenerateWarning())
          .build())
      .addAnnotation(AnnotationSpec.builder(RunWith.class)
          .addMember("value", "$T.class", OrderedRunner.class)
          .build())
      .addMethods(methodSpecs)
      .build();
}
项目:beam    文件:SorterTestUtils.java   
/** Tests trying to call add after calling sort. Should throw an exception. */
public static void testAddAfterSort(Sorter sorter, ExpectedException thrown) throws Exception {
  thrown.expect(IllegalStateException.class);
  thrown.expectMessage(is("Records can only be added before sort()"));
  KV<byte[], byte[]> kv = KV.of(new byte[] {4, 7}, new byte[] {1, 2});
  sorter.add(kv);
  sorter.sort();
  sorter.add(kv);
}
项目:beam    文件:SorterTestUtils.java   
/** Tests trying to calling sort twice. Should throw an exception. */
public static void testSortTwice(Sorter sorter, ExpectedException thrown) throws Exception {
  thrown.expect(IllegalStateException.class);
  thrown.expectMessage(is("sort() can only be called once."));
  KV<byte[], byte[]> kv = KV.of(new byte[] {4, 7}, new byte[] {1, 2});
  sorter.add(kv);
  sorter.sort();
  sorter.sort();
}
项目:easy-mybatis    文件:MybatisDaoTest.java   
@After
public void tearDown() throws Exception {
    //单个测试案例执行完之后,引用置空,防止数据污染
    tEmployee = null;
    tEmployeeExample = null;
    expectedException = ExpectedException.none();
}
项目:NFVO    文件:NetworkServiceDescriptorManagementClassSuiteTest.java   
@Test
public void nsdManagementOnboardTest()
    throws NotFoundException, BadFormatException, NetworkServiceIntegrityException,
        CyclicDependenciesException, EntityInUseException, BadRequestException, IOException,
        AlreadyExistingException, PluginException, IncompatibleVNFPackage, VimException,
        InterruptedException, EntityUnreachableException {

  NetworkServiceDescriptor nsd_exp = createNetworkServiceDescriptor();

  when(vnfmManagerEndpointRepository.findAll())
      .thenReturn(
          new ArrayList<VnfmManagerEndpoint>() {
            {
              VnfmManagerEndpoint vnfmManagerEndpoint = new VnfmManagerEndpoint();
              vnfmManagerEndpoint.setEndpoint("test");
              vnfmManagerEndpoint.setType("test");
              vnfmManagerEndpoint.setActive(true);
              vnfmManagerEndpoint.setEnabled(true);
              add(vnfmManagerEndpoint);
            }
          });

  when(nsdRepository.save(nsd_exp)).thenReturn(nsd_exp);
  exception = ExpectedException.none();
  nsdManagement.onboard(nsd_exp, projectId);
  assertEqualsNSD(nsd_exp);
}
项目:candybean    文件:WSSystemTest.java   
@Test
public void testHTTPError() {
    ExpectedException exception = ExpectedException.none();
    try {
        exception.expect(CandybeanException.class);
        response = WS.request(WS.OP.POST, uri + "/get", headers, "", ContentType.DEFAULT_TEXT);
        Assert.fail();
    } catch (CandybeanException e) {
        Assert.assertEquals("HTTP request received HTTP code: 405",
                e.getMessage().split("\n")[0]);
    }
}
项目:candybean    文件:WSSystemTest.java   
@Test
@Ignore("This test should pass, but takes a full minute to do so because it" +
        "waits for the response to time out.")
public void testResponseError() {
    ExpectedException exception = ExpectedException.none();
    try {
        exception.expect(CandybeanException.class);
        // Send to an IP address that does not exist
        response = WS.request(WS.OP.POST, "http://240.0.0.0", headers, "", ContentType.DEFAULT_TEXT);
        Assert.fail();
    } catch (CandybeanException e) {
        Assert.assertEquals("Connect to 240.0.0.0:80 [/240.0.0.0] failed: Operation timed out", e.getMessage());
    }
}
项目:r8    文件:R8RunExamplesTest.java   
@Test
public void outputIsIdentical() throws IOException, InterruptedException, ExecutionException {
  if (!ToolHelper.artSupported()) {
    return;
  }

  String original = getOriginalDexFile().toString();

  File generated;
  // Collect the generated dex files.
  File[] outputFiles =
      temp.getRoot().listFiles((File file) -> file.getName().endsWith(".dex"));
  if (outputFiles.length == 1) {
    // Just run Art on classes.dex.
    generated = outputFiles[0];
  } else {
    // Run Art on JAR file with multiple dex files.
    generated = temp.getRoot().toPath().resolve(pkg + ".jar").toFile();
    JarBuilder.buildJar(outputFiles, generated);
  }

  ToolHelper.ProcessResult javaResult =
      ToolHelper.runJava(ImmutableList.of(getOriginalJarFile().toString()), mainClass);
  if (javaResult.exitCode != 0) {
    fail("JVM failed for: " + mainClass);
  }

  // TODO(ager): Once we have a bot running using dalvik (version 4.4.4) we should remove
  // this explicit loop to get rid of repeated testing on the buildbots.
  for (DexVm version : artVersions) {
    TestCondition condition = failingRun.get(mainClass);
    if (condition != null && condition.test(tool, compiler, version, mode)) {
      thrown.expect(Throwable.class);
    } else {
      thrown = ExpectedException.none();
    }

    // Check output against Art output on original dex file.
    String output =
        ToolHelper.checkArtOutputIdentical(original, generated.toString(), mainClass, version);

    // Check output against JVM output.
    if (shouldMatchJVMOutput(version)) {
      String javaOutput = javaResult.stdout;
      assertEquals(
          "JVM and Art output differ:\n" + "JVM:\n" + javaOutput + "\nArt:\n" + output,
          output,
          javaOutput);
    }
  }
}
项目:spring-boot-gae    文件:ObjectifyTest.java   
public ExpectedException thrown() {
    return thrown;
}
项目:ArchUnit    文件:JavaClassTest.java   
public static void expectInvalidSyntaxUsageForClassInsteadOfInterface(ExpectedException thrown, Class<?> nonInterface) {
    thrown.expect(InvalidSyntaxUsageException.class);
    thrown.expectMessage(nonInterface.getName());
    thrown.expectMessage("interface");
}
项目:ArchUnit    文件:CanBeAnnotatedTest.java   
public static void expectInvalidSyntaxUsageForRetentionSource(ExpectedException thrown) {
    thrown.expect(InvalidSyntaxUsageException.class);
    thrown.expectMessage(Retention.class.getSimpleName());
    thrown.expectMessage(RetentionPolicy.SOURCE.name());
    thrown.expectMessage("useless");
}
项目:monarch    文件:ExpectedTimeoutRule.java   
private ExpectedTimeoutRule() {
  this.delegate = ExpectedException.none();
}
项目:DependencyInjector    文件:TestUtils.java   
public ExceptionCatcher(ExpectedException expectedException) {
    this.expectedException = expectedException;
}
项目:bowman    文件:ReflectionSupportTest.java   
@Rule
public ExpectedException getThrown() {
    return thrown;
}
项目:bowman    文件:DefaultTypeResolverTest.java   
@Rule
public ExpectedException getThrown() {
    return thrown;
}
项目:bowman    文件:DefaultPropertyValueFactoryTest.java   
@Rule
public ExpectedException getThrown() {
    return thrown;
}
项目:bowman    文件:RestOperationsTest.java   
@Rule
public ExpectedException getThrown() {
    return thrown;
}
项目:bowman    文件:JavassistClientProxyFactoryTest.java   
@Rule
public ExpectedException getThrown() {
    return thrown;
}
项目:bowman    文件:HalSupportTest.java   
@Rule
public ExpectedException getThrown() {
    return thrown;
}
项目:JavaVisGeekCollections    文件:Assert2.java   
public static void assertNullPointerExceptionThrown(ExpectedException expectedException, String expectMessage) {
    expectedException.expect(NullPointerException.class);
    expectedException.expectMessage(expectMessage);
}
项目:vespa    文件:JsonReaderTestCase.java   
@After
public void tearDown() throws Exception {
    types = null;
    parserFactory = null;
    exception = ExpectedException.none();
}
项目:beam    文件:ElasticsearchIOTestCommon.java   
void setExpectedException(ExpectedException expectedException) {
  this.expectedException = expectedException;
}
项目:flink    文件:BlobServerCorruptionTest.java   
/**
 * Checks the GET operation fails when the downloaded file (from HA store)
 * is corrupt, i.e. its content's hash does not match the {@link BlobKey}'s hash.
 *
 * @param config
 *      blob server configuration (including HA settings like {@link HighAvailabilityOptions#HA_STORAGE_PATH}
 *      and {@link HighAvailabilityOptions#HA_CLUSTER_ID}) used to set up <tt>blobStore</tt>
 * @param blobStore
 *      shared HA blob store to use
 * @param expectedException
 *      expected exception rule to use
 */
public static void testGetFailsFromCorruptFile(
        Configuration config, BlobStore blobStore, ExpectedException expectedException)
        throws IOException {

    Random rnd = new Random();
    JobID jobId = new JobID();

    try (BlobServer server = new BlobServer(config, blobStore)) {

        server.start();

        byte[] data = new byte[2000000];
        rnd.nextBytes(data);

        // put content addressable (like libraries)
        BlobKey key = put(server, jobId, data, PERMANENT_BLOB);
        assertNotNull(key);

        // delete local file to make sure that the GET requests downloads from HA
        File blobFile = server.getStorageLocation(jobId, key);
        assertTrue(blobFile.delete());

        // change HA store file contents to make sure that GET requests fail
        byte[] data2 = Arrays.copyOf(data, data.length);
        data2[0] ^= 1;
        File tmpFile = Files.createTempFile("blob", ".jar").toFile();
        try {
            FileUtils.writeByteArrayToFile(tmpFile, data2);
            blobStore.put(tmpFile, jobId, key);
        } finally {
            //noinspection ResultOfMethodCallIgnored
            tmpFile.delete();
        }

        // issue a GET request that fails
        expectedException.expect(IOException.class);
        expectedException.expectMessage("data corruption");

        get(server, jobId, key);
    }
}
项目:callfire-api-client-java    文件:AbstractIntegrationTest.java   
protected void expect404NotFoundCallfireApiException(ExpectedException ex) {
    ex.expect(CallfireApiException.class);
    ex.expect(hasProperty("apiErrorMessage", hasProperty("httpStatusCode", Matchers.is(404))));
}
项目:spring-cloud-zookeeper    文件:ZookeeperConfigAutoConfigurationTests.java   
@Before
public void setUp() throws Exception {
    expectedException = ExpectedException.none();
    // makes Curator fail faster, otherwise it takes 15 seconds to trigger a retry
    System.setProperty("curator-default-connection-timeout", "0");
}
项目:error-prone    文件:CheckReturnValuePositiveCases.java   
public void testBeforeAndAfterRule() {
  // BUG: Diagnostic contains: remove this line
  new IntValue(1).increment();
  ExpectedException.none().expect(IllegalStateException.class);
  new IntValue(1).increment(); // No error here, last statement in block
}
项目:mongo-rest    文件:DocumentValidationTest.java   
public void testInvalidFind(InvalidDocumentTestResult<T> result) {
    rule = ExpectedException.none();
    rule.expect(result.getExceptionClass());
    T document = service.findOne(result.getDocument().getId());
}
项目:mongo-rest    文件:DocumentValidationTest.java   
public void testInvalidSave(InvalidDocumentTestResult<T> result) throws Exception {
    rule = ExpectedException.none();
    rule.expect(result.getExceptionClass());
    service.create((T) result.getDocument());
}
项目:cs-actions    文件:MockingHelper.java   
@SuppressWarnings("unchecked")
public static void setExpectedExceptions(ExpectedException exception, Class<?> type, String message) {
    exception.expect((Class<? extends Throwable>) type);
    exception.expectMessage(message);
}
项目:cs-actions    文件:TestUtils.java   
@SuppressWarnings("unchecked")
public static void setExpectedExceptions(Class<?> type, ExpectedException exception, String message) {
    exception.expect((Class<? extends Throwable>) type);
    exception.expectMessage(message);
}
项目:hamcrest-submatcher    文件:SpyHolderTest.java   
@Rule
public ExpectedException getThrown()
{
    return thrown;
}
项目:hamcrest-submatcher    文件:MethodInvocationTest.java   
@Rule
public ExpectedException getThrown()
{
    return thrown;
}
项目:hamcrest-submatcher    文件:HasValueMatcherTest.java   
@Rule
public ExpectedException getThrown()
{
    return thrown;
}
项目:hamcrest-submatcher    文件:PreconditionsTest.java   
@Rule
public ExpectedException getThrown()
{
    return thrown;
}
项目:hamcrest-submatcher    文件:SpyTest.java   
@Rule
public ExpectedException getThrown()
{
    return thrown;
}