javatips.net counter

Java Examples for org.hamcrest.CoreMatchers

The following java examples will help you to understand the usage of org.hamcrest.CoreMatchers. These source code samples are taken from different open source projects.

Example 1
Project: RoboBuggy-master  File: ExpectedExceptionTest.java View source code
@Parameters(name = "{0}")
public static Collection<Object[]> testsWithEventMatcher() {
    return asList(new Object[][] { { EmptyTestExpectingNoException.class, everyTestRunSuccessful() }, { ThrowExceptionWithExpectedType.class, everyTestRunSuccessful() }, { ThrowExceptionWithExpectedPartOfMessage.class, everyTestRunSuccessful() }, { ThrowExceptionWithWrongType.class, hasSingleFailureWithMessage(startsWith("\nExpected: an instance of java.lang.NullPointerException")) }, { HasWrongMessage.class, hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"expectedMessage\"\n" + "     but: message was \"actualMessage\"")) }, { ThrowNoExceptionButExpectExceptionWithType.class, hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.NullPointerException") }, { WronglyExpectsExceptionMessage.class, hasSingleFailure() }, { ExpectsSubstring.class, everyTestRunSuccessful() }, { ExpectsSubstringNullMessage.class, hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"anything!\"")) }, { ExpectsMessageMatcher.class, everyTestRunSuccessful() }, { ExpectedMessageMatcherFails.class, hasSingleFailureWithMessage(startsWith("\nExpected: exception with message \"Wrong start\"")) }, { ExpectsMatcher.class, everyTestRunSuccessful() }, { ExpectAssertionErrorWhichIsNotThrown.class, hasSingleFailure() }, { FailedAssumptionAndExpectException.class, hasSingleAssumptionFailure() }, { FailBeforeExpectingException.class, hasSingleFailureWithMessage(ARBITRARY_MESSAGE) }, { ExpectsMultipleMatchers.class, hasSingleFailureWithMessage(startsWith("\nExpected: (an instance of java.lang.IllegalArgumentException and exception with message a string containing \"Ack!\")")) }, { ThrowExceptionWithMatchingCause.class, everyTestRunSuccessful() }, { ThrowExpectedNullCause.class, everyTestRunSuccessful() }, { ThrowUnexpectedCause.class, hasSingleFailureWithMessage(CoreMatchers.<String>allOf(startsWith("\nExpected: ("), containsString("exception with cause is <java.lang.NullPointerException: expected cause>"), containsString("cause was <java.lang.NullPointerException: an unexpected cause>"), containsString("Stacktrace was: java.lang.IllegalArgumentException: Ack!"), containsString("Caused by: java.lang.NullPointerException: an unexpected cause"))) }, { UseNoCustomMessage.class, hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.IllegalArgumentException") }, { UseCustomMessageWithoutPlaceHolder.class, hasSingleFailureWithMessage(ARBITRARY_MESSAGE) }, { UseCustomMessageWithPlaceHolder.class, hasSingleFailureWithMessage(ARBITRARY_MESSAGE + " - an instance of java.lang.IllegalArgumentException") } });
}
Example 2
Project: org.ops4j.pax.url-master  File: MetaTypeTest.java View source code
@Test
public void checkMetadata() throws IOException, BundleException {
    Bundle bundle = BundleUtils.getBundle(bc, "org.ops4j.pax.url.mvn");
    assertThat(bundle, is(notNullValue()));
    MetaTypeInformation metaTypeInformation = metaTypeService.getMetaTypeInformation(bundle);
    assertThat(metaTypeInformation, is(notNullValue()));
    String[] pids = metaTypeInformation.getPids();
    assertThat(pids, is(notNullValue()));
    assertThat(pids.length, is(1));
    assertThat(pids[0], is("org.ops4j.pax.url.mvn"));
    ObjectClassDefinition ocd = metaTypeInformation.getObjectClassDefinition(pids[0], null);
    assertThat(ocd, is(notNullValue()));
    assertThat(ocd.getID(), is("org.ops4j.pax.url.mvn"));
    AttributeDefinition[] attrDefs = ocd.getAttributeDefinitions(ObjectClassDefinition.ALL);
    assertThat(attrDefs, is(notNullValue()));
    assertThat(attrDefs.length, is(10));
    List<String> ids = new ArrayList<String>();
    for (AttributeDefinition attrDef : attrDefs) {
        String id = attrDef.getID().replace("org.ops4j.pax.url.mvn.", "");
        ids.add(id);
    }
    assertThat(ids, CoreMatchers.hasItems("certificateCheck", "defaultRepositories", "globalUpdatePolicy", "localRepository", "proxies", "proxySupport", "repositories", "security", "settings", "timeout"));
}
Example 3
Project: octarine-master  File: RecordJoinerTest.java View source code
@Test
public void three_way_join() {
    List<Record> joined = RecordJoins.join(RecordJoins.join(books).on(authorId).to(id).manyToOne(authors)).on(publisherId).to(id).manyToOne(publishers).map( r -> r.select(publisherName, authorName, bookName)).filter(authorName.is("Alan Goodyear")).collect(Collectors.toList());
    assertThat(joined, CoreMatchers.hasItems($$(bookName.of("Amorous Encounters"), authorName.of("Alan Goodyear"), publisherName.of("Bills And Moon")), $$(bookName.of("The Cromulence Of Truths"), authorName.of("Alan Goodyear"), publisherName.of("Servo"))));
}
Example 4
Project: Inside_Android_Testing-master  File: ApiGatewayTest.java View source code
@Test
public void shouldMakeRemoteGetCalls() {
    Robolectric.getBackgroundScheduler().pause();
    TestGetRequest apiRequest = new TestGetRequest();
    apiGateway.makeRequest(apiRequest, responseCallbacks);
    Robolectric.addPendingHttpResponse(200, GENERIC_XML);
    Robolectric.getBackgroundScheduler().runOneTask();
    HttpRequestInfo sentHttpRequestData = Robolectric.getSentHttpRequestInfo(0);
    HttpRequest sentHttpRequest = sentHttpRequestData.getHttpRequest();
    assertThat(sentHttpRequest.getRequestLine().getUri(), equalTo("www.example.com"));
    assertThat(sentHttpRequest.getRequestLine().getMethod(), equalTo(HttpGet.METHOD_NAME));
    assertThat(sentHttpRequest.getHeaders("foo")[0].getValue(), equalTo("bar"));
    CredentialsProvider credentialsProvider = (CredentialsProvider) sentHttpRequestData.getHttpContext().getAttribute(ClientContext.CREDS_PROVIDER);
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getUserPrincipal().getName(), CoreMatchers.equalTo("spongebob"));
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getPassword(), CoreMatchers.equalTo("squarepants"));
}
Example 5
Project: enviroCar-app-master  File: ObfuscationTest.java View source code
@Test
public void testObfuscation() throws JSONException, TrackAlreadyFinishedException, NoMeasurementsException {
    start = System.currentTimeMillis();
    end = System.currentTimeMillis() + 1000 * 60 * 100;
    first = new MeasurementImpl(51.0, 7.0);
    first.setTime(start);
    last = new MeasurementImpl(51.03, 7.03);
    last.setTime(end);
    //all intermediates should make it!
    inter = createIntermediates();
    Track t = createTrack();
    TrackSerializer s = new TrackSerializer();
    String ts = s.serialize(t, Track.class, null).toString();
    List<Measurement> result = TrackUtils.getObfuscatedTrack(t).getMeasurements();
    Assert.assertTrue("Unexpected element count", result.size() == TARGET_LENGTH);
    for (Measurement m : inter) {
        Assert.assertThat(result.contains(m), CoreMatchers.is(true));
    }
}
Example 6
Project: flink-master  File: RequiredParametersTest.java View source code
@Test
public void testPrintHelpForFullySetOption() {
    RequiredParameters required = new RequiredParameters();
    try {
        required.add(new Option("option").defaultValue("some").help("help").alt("o").choices("some", "options"));
        String helpText = required.getHelp();
        Assert.assertThat(helpText, CoreMatchers.allOf(containsString("Required Parameters:"), containsString("-o, --option"), containsString("default: some"), containsString("choices: "), containsString("some"), containsString("options")));
    } catch (RequiredParametersException e) {
        fail("Exception thrown " + e.getMessage());
    }
}
Example 7
Project: spring4-showcase-master  File: ServerControllerTest.java View source code
@Test
public void test11() throws Exception {
    //异步测试
    //Callable
    MvcResult result = //执行请求
    mockMvc.perform(get("/user/async1?id=1&name=zhang")).andExpect(request().asyncStarted()).andExpect(//默认会等10秒超时
    request().asyncResult(CoreMatchers.instanceOf(User.class))).andReturn();
    mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$.id").value(1));
    //DeferredResult
    result = //执行请求
    mockMvc.perform(get("/user/async2?id=1&name=zhang")).andExpect(request().asyncStarted()).andExpect(//默认会等10秒超时
    request().asyncResult(CoreMatchers.instanceOf(User.class))).andReturn();
    mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$.id").value(1));
}
Example 8
Project: bitcoinj-master  File: TransactionOutputTest.java View source code
@Test
public void testMultiSigOutputToString() throws Exception {
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN);
    ECKey myKey = new ECKey();
    this.wallet.importKey(myKey);
    // Simulate another signatory
    ECKey otherKey = new ECKey();
    // Create multi-sig transaction
    Transaction multiSigTransaction = new Transaction(PARAMS);
    ImmutableList<ECKey> keys = ImmutableList.of(myKey, otherKey);
    Script scriptPubKey = ScriptBuilder.createMultiSigOutputScript(2, keys);
    multiSigTransaction.addOutput(Coin.COIN, scriptPubKey);
    SendRequest req = SendRequest.forTx(multiSigTransaction);
    this.wallet.completeTx(req);
    TransactionOutput multiSigTransactionOutput = multiSigTransaction.getOutput(0);
    assertThat(multiSigTransactionOutput.toString(), CoreMatchers.containsString("CHECKMULTISIG"));
}
Example 9
Project: richfaces-master  File: ScriptUtilsTest.java View source code
@Test
public void testTimezoneSerialization() throws Exception {
    TimeZone utcPlusTwoTZ = TimeZone.getTimeZone("GMT+02:00");
    String serializedUTCPlusTwoTZ = dehydrate(ScriptUtils.toScript(utcPlusTwoTZ));
    assertThat(serializedUTCPlusTwoTZ, CoreMatchers.containsString("\"DSTSavings\":0"));
    assertThat(serializedUTCPlusTwoTZ, CoreMatchers.containsString("\"ID\":\"GMT+02:00\""));
    assertThat(serializedUTCPlusTwoTZ, CoreMatchers.containsString("\"rawOffset\":7200000"));
    TimeZone pstTimeZone = TimeZone.getTimeZone("PST");
    String serializedPSTTimeZone = dehydrate(ScriptUtils.toScript(pstTimeZone));
    assertThat(serializedPSTTimeZone, CoreMatchers.containsString("\"ID\":\"PST\""));
    assertThat(serializedPSTTimeZone, CoreMatchers.containsString("\"rawOffset\":-28800000"));
    TimeZone sfTimeZone = TimeZone.getTimeZone("America/New_York");
    String serializedSFTimeZone = dehydrate(ScriptUtils.toScript(sfTimeZone));
    assertThat(serializedSFTimeZone, CoreMatchers.containsString("\"ID\":\"America\\/New_York\""));
    assertThat(serializedSFTimeZone, CoreMatchers.containsString("\"rawOffset\":-18000000"));
}
Example 10
Project: hibernate-core-ogm-master  File: HibernateCacheTest.java View source code
@Test
public void testStaleWritesLeaveCacheConsistent() {
    Session s = getSessionFactory().openSession();
    Transaction txn = s.beginTransaction();
    VersionedItem item = new VersionedItem();
    item.setName("steve");
    item.setDescription("steve's item");
    s.save(item);
    txn.commit();
    s.close();
    Long initialVersion = item.getVersion();
    // manually revert the version property
    item.setVersion(item.getVersion() - 1);
    try {
        s = getSessionFactory().openSession();
        txn = s.beginTransaction();
        s.update(item);
        txn.commit();
        s.close();
        fail("expected stale write to fail");
    } catch (Throwable expected) {
        if (txn != null) {
            try {
                txn.rollback();
            } catch (Throwable ignore) {
            }
        }
    } finally {
        if (s != null && s.isOpen()) {
            try {
                s.close();
            } catch (Throwable ignore) {
            }
        }
    }
    // check the version value in the cache...
    SecondLevelCacheStatistics slcs = getSessionFactory().getStatistics().getSecondLevelCacheStatistics(REGION_PREFIX + VersionedItem.class.getName());
    assertThat(slcs, CoreMatchers.<Object>notNullValue());
    final Map entries = slcs.getEntries();
    Object entry = entries.get(item.getId());
    Long cachedVersionValue;
    if (entry instanceof SoftLock) {
    //FIXME don't know what to test here
    //cachedVersionValue = new Long( ( (ReadWriteCache.Lock) entry).getUnlockTimestamp() );
    } else {
        cachedVersionValue = (Long) ((Map) entry).get("_version");
        assertThat(initialVersion, equalTo(cachedVersionValue));
    }
    // cleanup
    s = getSessionFactory().openSession();
    txn = s.beginTransaction();
    item = (VersionedItem) s.load(VersionedItem.class, item.getId());
    s.delete(item);
    txn.commit();
    s.close();
}
Example 11
Project: wildfly-core-master  File: ContentRepositoryTest.java View source code
@Test
public void testListContents() throws Exception {
    byte[] archive = createArchive(Collections.singletonList("overlay.xhtml"));
    try (ByteArrayInputStream stream = new ByteArrayInputStream(archive)) {
        byte[] hash = repository.explodeContent(repository.addContent(stream));
        String expResult = "b1f18e286615dda0643633ec31f1a17d90e48875";
        //hash is different from the simple overlay.xhtml as we add the content folder name in the computation
        assertThat(hash, is(notNullValue()));
        Path content = repository.getContent(hash).getPhysicalFile().toPath();
        String contentHtml = readFileContent(content.resolve("overlay.xhtml"));
        String expectedContentHtml = readFileContent(getResourceAsStream("overlay.xhtml"));
        assertThat(contentHtml, is(expectedContentHtml));
        assertThat(HashUtil.bytesToHexString(hash), is(expResult));
        String updatedExpectedResult = "161a2c95b16d5ffede0721c2cec984ca51009082";
        hash = repository.addContentToExploded(hash, Collections.singletonList(new ExplodedContent("test.jsp", new ByteArrayInputStream("this is a test".getBytes(StandardCharsets.UTF_8)))), true);
        assertThat(hash, is(notNullValue()));
        assertThat(HashUtil.bytesToHexString(hash), is(updatedExpectedResult));
        List<String> contents = repository.listContent(hash, "", ContentFilter.Factory.createContentFilter(-1, false)).stream().map(ContentRepositoryElement::getPath).collect(Collectors.toList());
        assertThat(contents.size(), is(2));
        assertThat(contents, CoreMatchers.hasItems("test.jsp", "overlay.xhtml"));
        hash = repository.addContentToExploded(hash, Collections.singletonList(new ExplodedContent("test/empty-file.txt", emptyStream())), true);
        hash = repository.addContentToExploded(hash, Collections.singletonList(new ExplodedContent("empty-dir", null)), true);
        contents = repository.listContent(hash, "", ContentFilter.Factory.createContentFilter(-1, false)).stream().map(ContentRepositoryElement::getPath).collect(Collectors.toList());
        assertThat(contents, is(notNullValue()));
        assertThat(contents.size(), is(5));
        assertThat(contents, CoreMatchers.hasItems("test.jsp", "overlay.xhtml", "test/empty-file.txt", "test/", "empty-dir/"));
        hash = repository.removeContentFromExploded(hash, Collections.singletonList("test.jsp"));
        contents = repository.listContent(hash, "", ContentFilter.Factory.createFileFilter(-1, false)).stream().map(ContentRepositoryElement::getPath).collect(Collectors.toList());
        assertThat(contents, is(notNullValue()));
        assertThat(contents.size(), is(2));
        assertThat(contents, CoreMatchers.hasItems("overlay.xhtml", "test/empty-file.txt"));
    }
}
Example 12
Project: tinkerpop-master  File: GremlinServerIntegrateTest.java View source code
@Test
public void shouldReceiveFailureOnBadGraphSONSerialization() throws Exception {
    final Cluster cluster = TestClientFactory.build().serializer(Serializers.GRAPHSON_V1D0).create();
    final Client client = cluster.connect();
    try {
        client.submit("def class C { def C getC(){return this}}; new C()").all().join();
        fail("Should throw an exception.");
    } catch (RuntimeException re) {
        final Throwable root = ExceptionUtils.getRootCause(re);
        assertThat(root.getMessage(), CoreMatchers.startsWith("Error during serialization: Direct self-reference leading to cycle (through reference chain:"));
        assertEquals(2, client.submit("1+1").all().join().get(0).getInt());
    } finally {
        cluster.close();
    }
}
Example 13
Project: voms-api-java-master  File: TestVOMSESLineParser.java View source code
@Test
public void tooMultiCall() {
    String line0 = "\"a\" \"voms.cern.ch\" \"15000\" \"DN=Illo\" \"alice\"";
    String line1 = "\"b\" \"voms.cern.ch\" \"15001\" \"DN=IllY\" \"bolice\"";
    VOMSESLineParser p = new VOMSESLineParser();
    VOMSServerInfo i0 = p.parse(line0);
    VOMSServerInfo i1 = p.parse(line1);
    assertThat(i0.getAlias(), CoreMatchers.equalTo("a"));
    assertThat(i0.getURL().toString(), CoreMatchers.equalTo("voms://voms.cern.ch:15000"));
    assertThat(i0.getVoName(), CoreMatchers.equalTo("alice"));
    assertThat(i1.getAlias(), CoreMatchers.equalTo("b"));
    assertThat(i1.getURL().toString(), CoreMatchers.equalTo("voms://voms.cern.ch:15001"));
    assertThat(i1.getVoName(), CoreMatchers.equalTo("bolice"));
}
Example 14
Project: mpos-ui.android.paybutton-master  File: TransactionActivityTest.java View source code
public void testSendReceipt() {
    initWithAmount(106);
    StatefulTransactionProviderProxyIdlingResource idlingResource = new StatefulTransactionProviderProxyIdlingResource();
    Espresso.registerIdlingResources(idlingResource);
    Espresso.onView(ViewMatchers.withId(R.id.mpu_send_button)).perform(ViewActions.click());
    Espresso.onView(ViewMatchers.withId(R.id.mpu_email_address_view)).perform(ViewActions.typeText("[email protected]"));
    Espresso.onView(ViewMatchers.withId(R.id.mpu_send_button)).perform(ViewActions.click());
    Espresso.onView(ViewMatchers.withId(R.id.mpu_send_button)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.onView(ViewMatchers.withText(R.string.MPUReceiptSent)).inRoot(RootMatchers.withDecorView(CoreMatchers.not(CoreMatchers.is(getActivity().getWindow().getDecorView())))).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.unregisterIdlingResources(idlingResource);
}