Java 类org.hamcrest.Matchers 实例源码

项目:obevo    文件:ChangeCommandSorterImplTest.java   
@Test
public void testSortWithFk() throws Exception {
    final ExecuteChangeCommand aTab1 = newIncrementalCommand(tableChangeType(), "ATab", "1", Sets.immutable.<String>of(), 1);
    final ExecuteChangeCommand aTab2 = newIncrementalCommand(tableChangeType(), "ATab", "2", Sets.immutable.<String>of(), 2);
    final ExecuteChangeCommand aTab3 = newIncrementalCommand(tableChangeType(), "ATab", "3", Sets.immutable.<String>of(), 3);
    final ExecuteChangeCommand bTab1 = newIncrementalCommand(tableChangeType(), "BTab", "1", Sets.immutable.<String>of(), 1);
    final ExecuteChangeCommand bTab2 = newIncrementalCommand(tableChangeType(), "BTab", "2", Sets.immutable.<String>of("ATab"), 2);
    final ExecuteChangeCommand bTab3 = newIncrementalCommand(tableChangeType(), "BTab", "3", Sets.immutable.<String>of(), 3);
    final ListIterable<ExecuteChangeCommand> sortedCommands = sorter.sort(Lists.mutable.of(
            aTab1
            , aTab2
            , aTab3
            , bTab1
            , bTab2
            , bTab3
    ), false);

    // assert basic order
    assertThat("aTab changes should be in order", sortedCommands.indexOf(aTab1), Matchers.lessThan(sortedCommands.indexOf(aTab2)));
    assertThat("aTab changes should be in order", sortedCommands.indexOf(aTab2), Matchers.lessThan(sortedCommands.indexOf(aTab3)));
    assertThat("bTab changes should be in order", sortedCommands.indexOf(bTab1), Matchers.lessThan(sortedCommands.indexOf(bTab2)));
    assertThat("bTab changes should be in order", sortedCommands.indexOf(bTab2), Matchers.lessThan(sortedCommands.indexOf(bTab3)));

    // assert cross-object dependency
    assertThat("assert bTab change depending on aTab comes after tabA", sortedCommands.indexOf(aTab1), Matchers.lessThan(sortedCommands.indexOf(bTab2)));
}
项目:gdl2    文件:PredicateTest.java   
@Test
public void can_evaluate_pathed_datetime_against_current_datetime_minus_12_month() throws Exception {
    // /data[at0001]/items[at0003]/value/value>=($currentDateTime.value-12,mo)
    DataInstance[] dataInstances = new DataInstance[1];
    dataInstances[0] = new DataInstance.Builder()
            .modelId("weight")
            .addValue("/data[at0001]/items[at0003]", DvDateTime.valueOf("2014-02-15T18:18:00"))
            .build();
    interpreter = new Interpreter(DvDateTime.valueOf("2015-01-10T00:00:00"));
    BinaryExpression binaryExpression = new BinaryExpression(
            new Variable(CURRENT_DATETIME, null, null, "value"),
            new QuantityConstant(new DvQuantity("mo", 12.0, 0)), OperatorKind.SUBTRACTION);
    BinaryExpression predicate = new BinaryExpression(Variable.createByPath("/data[at0001]/items[at0003]/value/value"),
            binaryExpression, OperatorKind.GREATER_THAN_OR_EQUAL);
    List<DataInstance> result = interpreter.evaluateDataInstancesWithPredicate(Arrays.asList(dataInstances), predicate, null);
    assertThat(result.size(), Matchers.is(1));
    assertThat(result.get(0).modelId(), is("weight"));
}
项目:camel    文件:ScalarTest.java   
/**
 * Make sure that equals and hash code are reflexive
 * and symmetric.
 */
@Test
public void equalsAndHashCode() {
    final String val = "test scalar value";
    final Scalar firstScalar = new Scalar(val);
    final Scalar secondScalar = new Scalar(val);

    MatcherAssert.assertThat(firstScalar, Matchers.equalTo(secondScalar));
    MatcherAssert.assertThat(secondScalar, Matchers.equalTo(firstScalar));

    MatcherAssert.assertThat(firstScalar, Matchers.equalTo(firstScalar));
    MatcherAssert.assertThat(firstScalar,
        Matchers.not(Matchers.equalTo(null)));

    MatcherAssert.assertThat(
        firstScalar.hashCode() == secondScalar.hashCode(), is(true)
    );
}
项目:spring-cloud-dashboard    文件:RuntimeCommandsTests.java   
@Test
public void testStatusWithoutSummary() {
    Collection<AppStatusResource> data = new ArrayList<>();
    data.add(appStatusResource1);
    data.add(appStatusResource2);
    PagedResources.PageMetadata metadata = new PagedResources.PageMetadata(data.size(), 1, data.size(), 1);
    PagedResources<AppStatusResource> result = new PagedResources<>(data, metadata);
    when(runtimeOperations.status()).thenReturn(result);
    Object[][] expected = new String[][] {
            {"1", "deployed", "2"},
            {"10", "deployed"},
            {"20", "deployed"},
            {"2", "undeployed", "0"}
    };
    TableModel model = runtimeCommands.list(false, null).getModel();
    for (int row = 0; row < expected.length; row++) {
        for (int col = 0; col < expected[row].length; col++) {
            assertThat(String.valueOf(model.getValue(row + 1, col)), Matchers.is(expected[row][col]));
        }
    }
}
项目:cactoos    文件:OffsetDateTimeOfTest.java   
@Test
public final void testParsingFormattedStringWithOffsetToOffsetDateTime() {
    MatcherAssert.assertThat(
        "Can't parse a OffsetDateTime with custom format.",
        new OffsetDateTimeOf(
            "2017-12-13 14:15:16",
            "yyyy-MM-dd HH:mm:ss",
            ZoneOffset.ofHours(1)
        ).value(),
        Matchers.is(
            OffsetDateTime.of(
                LocalDateTime.of(2017, 12, 13, 14, 15, 16),
                ZoneOffset.ofHours(1)
            )
        )
    );
}
项目:elasticsearch_my    文件:DateHistogramIT.java   
public void testEmptyAggregation() throws Exception {
    SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx")
            .setQuery(matchAllQuery())
            .addAggregation(histogram("histo").field("value").interval(1L).minDocCount(0)
                    .subAggregation(dateHistogram("date_histo").field("value").interval(1)))
            .execute().actionGet();

    assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
    Histogram histo = searchResponse.getAggregations().get("histo");
    assertThat(histo, Matchers.notNullValue());
    List<? extends Histogram.Bucket> buckets = histo.getBuckets();
    assertThat(buckets.size(), equalTo(3));

    Histogram.Bucket bucket = buckets.get(1);
    assertThat(bucket, Matchers.notNullValue());
    assertThat(bucket.getKeyAsString(), equalTo("1.0"));

    Histogram dateHisto = bucket.getAggregations().get("date_histo");
    assertThat(dateHisto, Matchers.notNullValue());
    assertThat(dateHisto.getName(), equalTo("date_histo"));
    assertThat(dateHisto.getBuckets().isEmpty(), is(true));

}
项目:crnk-framework    文件:CustomResourceFieldTest.java   
@Test
public void test() throws InstantiationException, IllegalAccessException {
    String url = getBaseUri() + "country/ch";
    io.restassured.response.Response getResponse = RestAssured.get(url);
    Assert.assertEquals(200, getResponse.getStatusCode());

    getResponse.then().assertThat().body("data.attributes.deText", Matchers.equalTo("Schweiz"));
    getResponse.then().assertThat().body("data.attributes.enText", Matchers.equalTo("Switzerland"));

    String patchData = "{'data':{'id':'ch','type':'country','attributes':{'deText':'Test','enText':'Switzerland','ctlActCd':true}}}".replaceAll("'", "\"");

    Response patchResponse = RestAssured.given().body(patchData.getBytes()).header("content-type", JsonApiMediaType.APPLICATION_JSON_API).when().patch(url);
    patchResponse.then().statusCode(HttpStatus.SC_OK);

    getResponse = RestAssured.get(url);
    Assert.assertEquals(200, getResponse.getStatusCode());
    getResponse.then().assertThat().body("data.attributes.deText", Matchers.equalTo("Test"));
    getResponse.then().assertThat().body("data.attributes.enText", Matchers.equalTo("Switzerland"));
}
项目:comdor    文件:ConfusedTestCase.java   
/**
 * Confused can start an 'unknown' command.
 * @throws Exception If something goes wrong.
 */
@Test
public void startsUnknownCommand() throws Exception {
    final Command com = Mockito.mock(Command.class);
    Mockito.when(com.type()).thenReturn("unknown");
    Mockito.when(com.language()).thenReturn(new English());

    final Knowledge confused = new Confused();

    Steps steps = confused.start(com, Mockito.mock(Log.class));
    MatcherAssert.assertThat(steps, Matchers.notNullValue());
    MatcherAssert.assertThat(
        steps instanceof GithubSteps, Matchers.is(true)
    );

}
项目:Parseux    文件:ExcelIteratorTest.java   
@Ignore
@Test
public void iteratedCorrectlyBetweenBlankSheet() throws IOException {
    MatcherAssert.assertThat(
        "Each rows are iterated correctly, between blank sheets",
        new IteratorIterable<>(
            new ExcelIterator(
                new XSSFWorkbook(
                    new ResourceAsStream("excel/test-between-blank-sheet.xlsx").stream()
                )
            )
        ),
        Matchers.contains(
            Matchers.is("jed,24.0"),
            Matchers.is("aisyl,20.0"),
            Matchers.is("linux,23.0"),
            Matchers.is("juan,29.0")
        )
    );
}
项目:incubator-servicecomb-java-chassis    文件:TestJaxrsProducerResponseMapper.java   
@Test
public void mapResponse_withHeaders() {
  MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
  headers.add("h", "v");

  new Expectations() {
    {
      jaxrsResponse.getStatusInfo();
      result = Status.OK;
      jaxrsResponse.getEntity();
      result = "result";
      jaxrsResponse.getHeaders();
      result = headers;
    }
  };
  Response response = mapper.mapResponse(null, jaxrsResponse);
  Assert.assertEquals(Status.OK, response.getStatus());
  Assert.assertEquals("result", response.getResult());
  Assert.assertEquals(1, response.getHeaders().getHeaderMap().size());
  Assert.assertThat(response.getHeaders().getHeader("h"), Matchers.contains("v"));
}
项目:java-memory-assistant    文件:E2eITest.java   
@Test
public void testAgentHeapAllocation() throws Exception {
  final Process process = createProcessBuilder(heapDumpFolder) //
      .withJvmArgument("-Xms8m") //
      .withJvmArgument("-Xmx8m") //
      .withSystemProperty(LOG_LEVEL, "ERROR") //
      .withSystemProperty(CHECK_INTERVAL, "1s") //
      .withSystemProperty(MAX_HEAP_DUMP_FREQUENCY, "1/3s") //
      .withSystemProperty(HEAP_MEMORY_USAGE_THRESHOLD, "1%") //
      .withSystemProperty("jma-test.mode", "direct_allocation") //
      .withSystemProperty("jma-test.allocation", "3MB") //
      .withSystemProperty("jma-test.log", "false") //
      .buildAndRunUntil(heapDumpCreatedIn(heapDumpFolder, 1, TimeUnit.MINUTES));

  assertThat(process.getErr(), hasNoErrors());
  assertThat(heapDumpFolder.listFiles(), is(not(Matchers.<File>emptyArray())));
}
项目:VKMusicUploader    文件:AdvancedTagVerifiedAlbumImageTest.java   
@Test
public void valid()
    throws InvalidDataException, IOException, UnsupportedTagException {
    final Path path = Paths.get("src/test/resources/album/test.mp3");
    MatcherAssert.assertThat(
        new AdvancedTagVerifiedAlbumImage(
            new AdvancedTagFromMp3File(
                new Mp3File(
                    path.toFile()
                )
            )
        ).construct().getAlbumImage(),
        Matchers.equalTo(
            Files.readAllBytes(this.image)
        )
    );
}
项目:camel    文件:RtYamlMappingTest.java   
/**
 * RtYamlMapping can return null if the specified key is missig.
 */
@Test
public void returnsNullOnMissingKey() {
    Map<YamlNode, YamlNode> mappings = new HashMap<>();
    mappings.put(new Scalar("key3"), Mockito.mock(YamlSequence.class));
    mappings.put(new Scalar("key1"), Mockito.mock(YamlMapping.class));
    RtYamlMapping map = new RtYamlMapping(mappings);
    MatcherAssert.assertThat(
        map.yamlSequence("key4"), Matchers.nullValue()
    );
    MatcherAssert.assertThat(
        map.yamlMapping("key4"), Matchers.nullValue()
    );
    MatcherAssert.assertThat(
        map.string("key4"), Matchers.nullValue()
    );
    MatcherAssert.assertThat(
        map.yamlSequence("key1"), Matchers.nullValue()
    );
}
项目:ServiceServer    文件:UserControllerTest.java   
@Test
public void testLogoutFailures() throws Exception {
    // PHONE_INVALID_FORMAT
    mockMvc.perform(post(URI_USER_LOGOUT)
        .param("phoneNum", TEST_PHONE_INVALID)
        .session(session))
        .andExpect(status().isBadRequest())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.*").value(Matchers.hasSize(2)))
        .andExpect(jsonPath("$.info").isString())
        .andExpect(jsonPath("$.code").value(100));
    // SESSION_NOT_FOUND
    mockMvc.perform(post(URI_USER_LOGOUT)
        .param("phoneNum", TEST_PHONE_USER))
        .andExpect(status().isForbidden())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.*").value(Matchers.hasSize(2)))
        .andExpect(jsonPath("$.info").isString())
        .andExpect(jsonPath("$.code").value(403));
}
项目:cactoos    文件:DateOfTest.java   
@Test
public final void testParsingCustomFormattedStringToDate() {
    MatcherAssert.assertThat(
        "Can't parse a Date with custom format.",
        new DateOf(
            "2017-12-13 14:15:16.000000017",
            "yyyy-MM-dd HH:mm:ss.n"
        ).value(),
        Matchers.is(
            Date.from(
                LocalDateTime.of(
                    2017, 12, 13, 14, 15, 16, 17
                ).toInstant(ZoneOffset.UTC)
            )
        )
    );
}
项目:cereebro    文件:SnitchEndpointConfigurationPropertiesDetectorTest.java   
@Test
public void testPropertiesRelationships() {
    // @formatter:off
    RestAssured
        .given()
        .when()
            .get(snitchURI)
        .then()
            .statusCode(200)
            .contentType(ContentType.JSON)
            .body("componentRelationships[0].component.name", Matchers.is("app-props-detector"))
            .body("componentRelationships[0].component.type", Matchers.is("properties/application"))
            .body("componentRelationships[0].dependencies", Matchers.hasSize(1))
            .body("componentRelationships[0].dependencies[0].component.name", Matchers.is("dependency"))
            .body("componentRelationships[0].dependencies[0].component.type", Matchers.is("properties/dependency"))
            .body("componentRelationships[0].consumers", Matchers.hasSize(1))
            .body("componentRelationships[0].consumers[0].component.name", Matchers.is("consumer"))
            .body("componentRelationships[0].consumers[0].component.type", Matchers.is("properties/consumer"));
    // @formatter:on
}
项目:ServiceServer    文件:SmsControllerTest.java   
@Test
@Ignore
public void testSendSms() throws Exception {
    // PHONE_INVALID_FORMAT
    mockMvc.perform(get(URI_SMS_GET, TEST_PHONE_INVALID))
        .andExpect(status().isBadRequest())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.*").value(Matchers.hasSize(2)))
        .andExpect(jsonPath("$.code").value(100));
    // Success
    mockMvc.perform(get(URI_SMS_GET, TEST_PHONE_USER))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.*").value(Matchers.hasSize(1)))
        .andExpect(jsonPath("$.phoneNum").value(TEST_PHONE_USER));
}
项目:HttpClientMock    文件:UrlParser.java   
public UrlConditions parse(String urlText) {
    try {
        UrlConditions conditions = new UrlConditions();
        URL url = new URL(urlText);
        if (url.getRef() != null) {
            conditions.setReferenceConditions(equalTo(url.getRef()));
        } else {
            conditions.setReferenceConditions(isEmptyOrNullString());
        }
        conditions.setSchemaConditions(Matchers.equalTo(url.getProtocol()));
        conditions.getHostConditions().add(equalTo(url.getHost()));
        conditions.getPortConditions().add(equalTo(url.getPort()));
        conditions.getPathConditions().add(equalTo(url.getPath()));
        List<NameValuePair> params = UrlParams.parse(url.getQuery(), Charset.forName("UTF-8"));
        for (NameValuePair param : params) {
            conditions.getParameterConditions().put(param.getName(), equalTo(param.getValue()));
        }
        return conditions;
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(e);
    }

}
项目:springmock    文件:DoubleSearchTest.java   
@Test
public void should_throw_exception_when_multiple_definitions_found_by_name_and_class() {
    //given
    final String mockName = "mock";
    final Class<?> mockClass = Service.class;
    final DoubleSearch search = new DoubleSearch(asList(
            doubleDefinition(mockClass, mockName),
            doubleDefinition(mockClass, mockName)));
    exception.expect(IllegalStateException.class);
    exception.expectMessage(Matchers.allOf(
            startsWith(MISSING_DOUBLE_EXCEPTION_PREFIX),
            containsString(MULTIPLE_DOUBLES_EXCEPTION_MESSAGE)));

    //when
    search.findOneDefinition(mockName, Service.class);
}
项目:elasticsearch_my    文件:MovAvgIT.java   
private void assertBucketContents(Histogram.Bucket actual, Double expectedCount, Double expectedValue) {
    // This is a gap bucket
    SimpleValue countMovAvg = actual.getAggregations().get("movavg_counts");
    if (expectedCount == null) {
        assertThat("[_count] movavg is not null", countMovAvg, nullValue());
    } else if (Double.isNaN(expectedCount)) {
        assertThat("[_count] movavg should be NaN, but is ["+countMovAvg.value()+"] instead", countMovAvg.value(), equalTo(Double.NaN));
    } else {
        assertThat("[_count] movavg is null", countMovAvg, notNullValue());
        assertTrue("[_count] movavg does not match expected [" + countMovAvg.value() + " vs " + expectedCount + "]",
                nearlyEqual(countMovAvg.value(), expectedCount, 0.1));
    }

    // This is a gap bucket
    SimpleValue valuesMovAvg = actual.getAggregations().get("movavg_values");
    if (expectedValue == null) {
        assertThat("[value] movavg is not null", valuesMovAvg, Matchers.nullValue());
    } else if (Double.isNaN(expectedValue)) {
        assertThat("[value] movavg should be NaN, but is ["+valuesMovAvg.value()+"] instead", valuesMovAvg.value(), equalTo(Double.NaN));
    } else {
        assertThat("[value] movavg is null", valuesMovAvg, notNullValue());
        assertTrue("[value] movavg does not match expected [" + valuesMovAvg.value() + " vs " + expectedValue + "]",
                nearlyEqual(valuesMovAvg.value(), expectedValue, 0.1));
    }
}
项目:googlecloud-techtalk    文件:DatastoreKeyRepositoryTest.java   
@SuppressWarnings("unchecked")
@Test
public void shouldDeleteEntitiesById() {
    DatastoreKeyTestEntity testEntity = new DatastoreKeyTestEntity(1, "name");
    DatastoreKeyTestEntity testEntity2 = new DatastoreKeyTestEntity(2, "name2");
    repository.putAsync(testEntity, testEntity2).complete();

    assertThat(repository.get(testEntity.getKey()), is(testEntity));
    assertThat(repository.get(testEntity2.getKey()), is(testEntity2));
    assertThat(repository.search().field("key", list(testEntity.getKey(), testEntity2.getKey())).run().getResults().size(), is(2));

    repository.deleteByKeyAsync(testEntity.getKey(), testEntity2.getKey()).complete();

    assertThat(repository.get(testEntity.getKey(), testEntity2.getKey()), Matchers.hasItems(nullValue(), nullValue()));
    assertThat(repository.search().field("key", list(testEntity.getKey(), testEntity2.getKey())).run().getResults().isEmpty(), is(true));
}
项目:xm-ms-entity    文件:TargetProceedingLepUnitTest.java   
@Test
public void voidMethodNoArgsBodyThrowsCustomThrowable() throws Exception {
    expectedEx.expect(IllegalStateException.class);
    expectedEx.expectMessage(Matchers.startsWith("Error processing target method for LEP resource key"));

    MethodSignature signature = Mockito.mock(MethodSignature.class);
    when(signature.getParameterTypes()).thenReturn(new Class<?>[0]);
    when(signature.getMethod()).thenReturn(voidMethodNoArgsCustomThrowable);

    LepMethod method = Mockito.mock(LepMethod.class);
    when(method.getMethodSignature()).thenReturn(signature);
    when(method.getTarget()).thenReturn(this);

    TargetProceedingLep proceedingLep = new TargetProceedingLep(method, null);
    proceedingLep.proceed();
}
项目:sunshine    文件:JunitStatusTest.java   
@Test
public void failureCount() {
    MatcherAssert.assertThat(
            new JunitStatus(new FakeResult(false, 0, 2, 0)).failureCount(),
            Matchers.is(2)
    );
}
项目:annotation-processor-toolkit    文件:FluentValidatorTest.java   
@Test
public void testOfSettingMessageLevel() {

    // check if message level is set and if same TestFluentValidator is returned

    // info
    TestFluentValidator<Element> nextFluentValidator = unit.info();
    MatcherAssert.assertThat(nextFluentValidator.getMessageLevel(), Matchers.is(Diagnostic.Kind.NOTE));
    MatcherAssert.assertThat(nextFluentValidator, Matchers.equalTo(unit));

    // warning
    nextFluentValidator = nextFluentValidator.warning();
    MatcherAssert.assertThat(nextFluentValidator.getMessageLevel(), Matchers.is(Diagnostic.Kind.WARNING));
    MatcherAssert.assertThat(nextFluentValidator, Matchers.equalTo(unit));

    // mandatory warning
    nextFluentValidator = nextFluentValidator.mandatoryWarning();
    MatcherAssert.assertThat(nextFluentValidator.getMessageLevel(), Matchers.is(Diagnostic.Kind.MANDATORY_WARNING));
    MatcherAssert.assertThat(nextFluentValidator, Matchers.equalTo(unit));

    // other
    nextFluentValidator = nextFluentValidator.other();
    MatcherAssert.assertThat(nextFluentValidator.getMessageLevel(), Matchers.is(Diagnostic.Kind.OTHER));
    MatcherAssert.assertThat(nextFluentValidator, Matchers.equalTo(unit));

    // error
    nextFluentValidator = nextFluentValidator.error();
    MatcherAssert.assertThat(nextFluentValidator.getMessageLevel(), Matchers.is(Diagnostic.Kind.ERROR));
    MatcherAssert.assertThat(nextFluentValidator, Matchers.equalTo(unit));

}
项目:dotwebstack-framework    文件:KeepAfterLastFunctionTest.java   
@Test
public void testNoOccurrence() throws ParseException {
  final String value = "stringLiteral";
  final String ldPath =
      String.format("fn:keepAfterLast(<%s>, \"%s\") :: xsd:string", predicate.stringValue(), "/");
  addStatement(repository.getValueFactory().createStatement(subject, predicate,
      repository.getValueFactory().createLiteral(value)));

  final ImmutableCollection<Object> values = evaluateRule(ldPath, subject);

  assertThat(values.size(), Matchers.equalTo(1));
  assertThat(values, Matchers.contains(value));
}
项目:gdl2    文件:FiredRulesTest.java   
@Test
public void can_evaluate_fired_rule_expected_false() throws Exception {
    guideline = loadGuideline(BSA_CALCULATION_FIRED_RULE);
    ArrayList<DataInstance> dataInstances = new ArrayList<>();
    dataInstances.add(toWeight("158.7,lbs"));
    dataInstances.add(toHeight("5.95,ft"));

    Map<String, Object> result = interpreter.execute(guideline, dataInstances);
    Object dataValue = result.get("gt0014");
    assertThat(dataValue, Matchers.instanceOf(DvBoolean.class));
    DvBoolean dvBoolean = (DvBoolean) dataValue;
    assertThat(dvBoolean.getValue(), is(false));
}
项目:cactoos    文件:FilteredTest.java   
@Test
public void withoutItemsIsEmpty() throws Exception {
    MatcherAssert.assertThat(
        new Filtered<String>(
            input -> input.length() > 16,
            new IterableOf<>("third", "fourth")
        ).isEmpty(),
        Matchers.equalTo(true)
    );
}
项目:RxShell    文件:CmdProcessorTest.java   
@Test(expected = IllegalStateException.class)
public void testNoReuse() throws IOException {
    processor.attach(session);

    final Cmd.Result result = processor.submit(Cmd.builder("echo straw").build()).test().awaitDone(3, TimeUnit.SECONDS).assertNoTimeout().values().get(0);
    assertThat(result.getExitCode(), is(RxProcess.ExitCode.OK));
    assertThat(result.getOutput(), Matchers.contains("straw"));

    session.cancel().test().awaitDone(1, TimeUnit.SECONDS).assertNoTimeout();

    MockRxShellSession mockSession2 = new MockRxShellSession();
    processor.attach(mockSession2.getSession());
}
项目:elasticsearch_my    文件:DateIndexNameFactoryTests.java   
public void testSpecifyOptionalSettings() throws Exception {
    DateIndexNameProcessor.Factory factory = new DateIndexNameProcessor.Factory();
    Map<String, Object> config = new HashMap<>();
    config.put("field", "_field");
    config.put("index_name_prefix", "_prefix");
    config.put("date_rounding", "y");
    config.put("date_formats", Arrays.asList("UNIX", "UNIX_MS"));

    DateIndexNameProcessor processor = factory.create(null, null, config);
    assertThat(processor.getDateFormats().size(), Matchers.equalTo(2));

    config = new HashMap<>();
    config.put("field", "_field");
    config.put("index_name_prefix", "_prefix");
    config.put("date_rounding", "y");
    config.put("index_name_format", "yyyyMMdd");

    processor = factory.create(null, null, config);
    assertThat(processor.getIndexNameFormat(), Matchers.equalTo("yyyyMMdd"));

    config = new HashMap<>();
    config.put("field", "_field");
    config.put("index_name_prefix", "_prefix");
    config.put("date_rounding", "y");
    config.put("timezone", "+02:00");

    processor = factory.create(null, null, config);
    assertThat(processor.getTimezone(), Matchers.equalTo(DateTimeZone.forOffsetHours(2)));

    config = new HashMap<>();
    config.put("field", "_field");
    config.put("index_name_prefix", "_prefix");
    config.put("date_rounding", "y");

    processor = factory.create(null, null, config);
    assertThat(processor.getIndexNamePrefix(), Matchers.equalTo("_prefix"));
}
项目:VKMusicUploader    文件:QueriesFromAttachmentsTest.java   
@Test
public void idsMap() throws IOException, ClientException, ApiException {
    final Map<Integer, String> expected = new HashMap<>();
    expected.put(0, "1");
    expected.put(1, "2");
    MatcherAssert.assertThat(
        this.queries.idsMap(),
        Matchers.equalTo(expected)
    );
}
项目:cactoos    文件:BehavesAsMap.java   
@Override
public boolean matchesSafely(final Map<K, V> map) {
    MatcherAssert.assertThat(map, Matchers.hasKey(this.key));
    MatcherAssert.assertThat(map, Matchers.hasValue(this.value));
    MatcherAssert.assertThat(map.keySet(), Matchers.hasItem(this.key));
    MatcherAssert.assertThat(map.values(), Matchers.hasItem(this.value));
    return true;
}
项目:camel    文件:ReadPipeScalarTest.java   
/**
 * ReadPipeScalar can compare itself to other ReadPipeScalar.
 */
@Test
public void comparesToReadPipeScalar() {
    final List<YamlLine> lines = new ArrayList<>();
    lines.add(new RtYamlLine("Java", 1));
    final ReadPipeScalar first = 
        new ReadPipeScalar(new RtYamlLines(lines));
    final ReadPipeScalar second = 
        new ReadPipeScalar(new RtYamlLines(lines));
    MatcherAssert.assertThat(first.compareTo(second), Matchers.is(0));
}
项目:cactoos    文件:DateAsTextTest.java   
@Test
public final void testZonedDateTimeFormattedAsIsoDateTime() {
    final ZonedDateTime date = ZonedDateTime.of(
        2017, 12, 13, 14, 15, 16, 17, ZoneId.of("Europe/Berlin")
    );
    MatcherAssert.assertThat(
        "Can't format a ZonedDateTime with default/ISO format.",
        new DateAsText(date).asString(),
        Matchers.is("2017-12-13T14:15:16.000000017+01:00")
    );
}
项目:xm-commons    文件:LepContextUtilsUnitTest.java   
@Test
public void whenNoThreadContextThenThrowException() {
    expectedEx.expect(IllegalStateException.class);
    expectedEx.expectMessage(Matchers.startsWith("LEP manager thread context doesn't initialized."));

    when(contextsHolder.getContext(eq(ContextScopes.THREAD))).thenReturn(null);

    LepContextUtils.getTenantKey(contextsHolder);
}
项目:comdor    文件:LastMentionTestCase.java   
/**
 * The bot understands a mention using the first language.
 * @throws Exception If something goes wrong.
 */
@Test
public void understandsWithFirstLanguage() throws Exception {
    final MkStorage storage = new MkStorage.Synced(new MkStorage.InFile());
    final Repo repoMihai = new MkGithub(storage, "amihaiemil")
        .repos().create(
            new Repos.RepoCreate("amihaiemil.github.io", false)
        );
    final Issue mihai = repoMihai.issues().create("test issue", "body");
    mihai.comments().post("@comdor hello!");

    final Issue comdor = new MkGithub(storage, "comdor").repos()
            .get(repoMihai.coordinates())
            .issues()
            .get(mihai.number());
    final Command last = new LastMention(comdor);
    MatcherAssert.assertThat(
        last.type(), Matchers.equalTo("unknown")
    );

    final Language first = Mockito.mock(Language.class);
    Mockito.when(first.categorize(last)).thenReturn("hello");

    final Language second = Mockito.mock(Language.class);
    Mockito.when(second.categorize(last)).thenReturn("hello");

    last.understand(first, second, Mockito.mock(Language.class));

    MatcherAssert.assertThat(
        last.type(), Matchers.equalTo("hello")
    );
    MatcherAssert.assertThat(
        last.language(), Matchers.is(first)
    );
}
项目:gdl2    文件:AggregationFunctionSumTest.java   
@Test
public void can_evaluation_sum_in_condition_with_dv_ordinal() throws Exception {
    Guideline guideline = loadGuideline("Sum_in_condition_test.v1.gdl2");
    ArrayList<DataInstance> dataInstances = new ArrayList<>();
    dataInstances.add(withOrdinal(50));
    dataInstances.add(withOrdinal(60));

    Map<String, Object> result = interpreter.execute(guideline, dataInstances);
    Object dataValue = result.get("gt0007");
    assertThat(dataValue, Matchers.instanceOf(DvText.class));
    DvText dvText = (DvText) dataValue;
    assertThat(dvText.getValue(), is("Overdose"));
}
项目:cactoos    文件:JoinedTest.java   
@Test
public void size() throws Exception {
    MatcherAssert.assertThat(
        new Joined<Integer>(
            new ListOf<>(1, 2),
            new ListOf<>(3, 4)
        ).size(),
        Matchers.equalTo(4)
    );
}
项目:elasticsearch_my    文件:AdjacencyMatrixIT.java   
public void testSimple() throws Exception {
    SearchResponse response = client().prepareSearch("idx")
            .addAggregation(adjacencyMatrix("tags",
                    newMap("tag1", termQuery("tag", "tag1")).add("tag2", termQuery("tag", "tag2"))))
            .execute().actionGet();

    assertSearchResponse(response);

    AdjacencyMatrix matrix = response.getAggregations().get("tags");
    assertThat(matrix, notNullValue());
    assertThat(matrix.getName(), equalTo("tags"));

    int expected = numMultiTagDocs > 0 ? 3 : 2;
    assertThat(matrix.getBuckets().size(), equalTo(expected));

    AdjacencyMatrix.Bucket bucket = matrix.getBucketByKey("tag1");
    assertThat(bucket, Matchers.notNullValue());
    assertThat(bucket.getDocCount(), equalTo((long) numTag1Docs));

    bucket = matrix.getBucketByKey("tag2");
    assertThat(bucket, Matchers.notNullValue());
    assertThat(bucket.getDocCount(), equalTo((long) numTag2Docs));

    bucket = matrix.getBucketByKey("tag1&tag2");
    if (numMultiTagDocs == 0) {
        assertThat(bucket, Matchers.nullValue());
    } else {
        assertThat(bucket, Matchers.notNullValue());
        assertThat(bucket.getDocCount(), equalTo((long) numMultiTagDocs));
    }

}
项目:camel    文件:StrictYamlSequenceTest.java   
/**
 * StringYamlSequence can fetch a YamlMapping based in its index.
 */
@Test
public void returnsMapping() {
    YamlSequence origin = Mockito.mock(YamlSequence.class);
    YamlMapping found = Mockito.mock(YamlMapping.class);
    Mockito.when(origin.yamlMapping(1)).thenReturn(found);
    YamlSequence strict = new StrictYamlSequence(origin);
    MatcherAssert.assertThat(
        strict.yamlMapping(1), Matchers.equalTo(found)
    );
}