Java 类org.hamcrest.MatcherAssert 实例源码

项目:VKMusicUploader    文件:WallPostFromGroupTest.java   
@Test
public void test() throws IOException {
    MatcherAssert.assertThat(
        "Incorrect query map produced.",
        new WallPostFromGroup(
            new WallPostBase(
                new VkApiClient(
                    new TransportClientCached(
                        ""
                    )
                ),
                new UserActor(
                    0,
                    "1"
                )
            )
        ).construct().build(),
        Matchers.allOf(
            Matchers.hasEntry("access_token", "1"),
            Matchers.hasEntry("v", "5.63"),
            Matchers.hasEntry("from_group", "1")
        )
    );
}
项目:cactoos    文件:SkippedTest.java   
@Test
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public void skipIterable() throws Exception {
    MatcherAssert.assertThat(
        "Can't skip elements in iterable",
        new Skipped<>(
            2, new IterableOf<>(
                "one", "two", "three", "four"
            )
        ),
        Matchers.contains(
            "three",
            "four"
        )
    );
}
项目:cactoos    文件:MapOfTest.java   
@Test
public void createsMapWithFunctions() {
    MatcherAssert.assertThat(
        "Can't create a map with functions as values",
        new MapOf<Integer, Scalar<Boolean>>(
            new MapEntry<>(0, () -> true),
            new MapEntry<>(
                1,
                () -> {
                    throw new IOException("oops");
                }
            )
        ),
        Matchers.hasKey(0)
    );
}
项目:cactoos    文件:ResourceOfTest.java   
@Test
public void readsBinaryResource() throws Exception {
    MatcherAssert.assertThat(
        "Can't read bytes from a classpath resource",
        Arrays.copyOfRange(
            new BytesOf(
                new ResourceOf(
                    "org/cactoos/io/ResourceOfTest.class"
                )
            ).asBytes(),
            // @checkstyle MagicNumber (2 lines)
            0,
            4
        ),
        Matchers.equalTo(
            new byte[]{
                // @checkstyle MagicNumber (1 line)
                (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE,
            }
        )
    );
}
项目: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)
    );
}
项目:Android-Migrator    文件:MigrationFileAssetTest.java   
private static void assertSize(
    final String file,
    final int size
) throws IOException {
    MatcherAssert.assertThat(
        file,
        Collections.list(
            new IterableEnum<>(
                new MigrationFileAsset(
                    RuntimeEnvironment.application.getAssets(),
                    new File("files", file)
                ).migrations()
            )
        ),
        Matchers.hasSize(size)
    );
}
项目:cactoos    文件:BytesOfTest.java   
@Test
public void readsInputIntoBytes() throws IOException {
    MatcherAssert.assertThat(
        "Can't read bytes from Input",
        new String(
            new BytesOf(
                new InputOf("Hello, друг!")
            ).asBytes(),
            StandardCharsets.UTF_8
        ),
        Matchers.allOf(
            Matchers.startsWith("Hello, "),
            Matchers.endsWith("друг!")
        )
    );
}
项目: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)
    );

}
项目:cactoos    文件:AsyncFuncTest.java   
@Test
public void runsAsProcInBackground() {
    MatcherAssert.assertThat(
        "Can't run proc in the background",
        input -> {
            final CountDownLatch latch = new CountDownLatch(1);
            new AsyncFunc<>(
                (Proc<Boolean>) ipt -> latch.countDown()
            ).exec(input);
            latch.await();
            return true;
        },
        new FuncApplies<>(
            true, Matchers.equalTo(true)
        )
    );
}
项目:versioneye-api    文件:RepositoriesPageTestCase.java   
/**
 * RepositoriesPage can return the first page of repositories.
 * @throws Exception If something goes wrong.
 */
@Test
public void iteratesOverFirstPage() throws Exception {
    final MkContainer container =
        this.mockVersionEyeRepositories().start();
    final VersionEye versionEye = new RtVersionEye(
        new JdkRequest(container.home())
    );
    List<Repository> first =
        versionEye.github().repositories().paginated().fetch();
    MatcherAssert.assertThat(first.size(), Matchers.is(14));
    MatcherAssert.assertThat(
        first.get(0).name(),
        Matchers.equalTo("Compiler")
    );
    MatcherAssert.assertThat(
        first.get(13).name(),
        Matchers.equalTo("versioneye-api")
    );
    MatcherAssert.assertThat(
        container.take().uri().toString(),
        Matchers.equalTo("/github?page=1")
    );   
}
项目:cactoos    文件:PartitionedTest.java   
@Test
public void partitionedOne() {
    MatcherAssert.assertThat(
        "Can't generate a Partitioned of partition size 1.",
        new ArrayList<>(
            new ListOf<>(
                new Partitioned<>(1, Arrays.asList(1, 2, 3).iterator())
            )
        ),
        Matchers.equalTo(
            Arrays.asList(
                Collections.singletonList(1), Collections.singletonList(2),
                Collections.singletonList(3)
            )
        )
    );
}
项目:polymorphia    文件:TestEnums.java   
@Test
public void testEnums() {
    Codec<Pojo> pojoCodec = codecRegistry.get(Pojo.class);

    LovelyDisplayable lovelyDisplayable = LovelyDisplayable.builder().identityProperty("foo").build();

    Pojo pojo = Pojo.builder()
            .simpleEnumProperty(EnumA.TYPE1)
            .displayable(Arrays.asList(EnumB.TYPE1, EnumA.TYPE1, EnumA.TYPE3, lovelyDisplayable))
            .build();

    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true));
    pojoCodec.encode(writer, pojo, EncoderContext.builder().build());
    System.out.println(stringWriter.toString());

    Pojo decodedPojo = pojoCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build());

    MatcherAssert.assertThat(decodedPojo.getDisplayable(),
            IsIterableContainingInOrder.contains(EnumB.TYPE1, EnumA.TYPE1, EnumA.TYPE3, lovelyDisplayable));

}
项目:cactoos    文件:BytesOfTest.java   
@Test
public void readsInputIntoBytesWithSmallBuffer() throws IOException {
    MatcherAssert.assertThat(
        "Can't read bytes from Input with a small reading buffer",
        new String(
            new BytesOf(
                new InputOf(
                    new TextOf("Hello, товарищ!")
                ),
                2
            ).asBytes(),
            StandardCharsets.UTF_8
        ),
        Matchers.allOf(
            Matchers.startsWith("Hello,"),
            Matchers.endsWith("товарищ!")
        )
    );
}
项目:annotation-processor-toolkit    文件:ElementUtils_AccessEnclosingElementsTest.java   
@Test
public void getFlattenedEnclosingElementsTree_withoutRoot_withMaxDepth() {

    // Prepare
    Element parameterElement = Mockito.mock(VariableElement.class);
    Element methodElement = Mockito.mock(ExecutableElement.class);
    Element typeElement = Mockito.mock(TypeElement.class);
    Element packageElement = Mockito.mock(PackageElement.class);

    Mockito.when(parameterElement.getEnclosingElement()).thenReturn(methodElement);
    Mockito.when(methodElement.getEnclosingElement()).thenReturn(typeElement);
    Mockito.when(typeElement.getEnclosingElement()).thenReturn(packageElement);

    // execute
    List<Element> result = ElementUtils.AccessEnclosingElements.getFlattenedEnclosingElementsTree(parameterElement, false, 2);

    // validate
    MatcherAssert.assertThat(result, Matchers.containsInAnyOrder(methodElement, typeElement));
    MatcherAssert.assertThat(result, Matchers.not(Matchers.contains(parameterElement, packageElement)));


}
项目:cactoos    文件:StickyMapTest.java   
@Test
public void ignoresChangesInMap() throws Exception {
    final AtomicInteger size = new AtomicInteger(2);
    final Map<Integer, Integer> map = new StickyMap<>(
        new MapOf<>(
            () -> new Repeated<>(
                size.incrementAndGet(), () -> new MapEntry<>(
                    new SecureRandom().nextInt(),
                    1
                )
            )
        )
    );
    MatcherAssert.assertThat(
        "Can't ignore the changes in the underlying map",
        map.size(),
        Matchers.equalTo(map.size())
    );
}
项目: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()
    );
}
项目:cactoos    文件:AndWithIndexTest.java   
@Test
public void iteratesListWithIndex() {
    final List<String> list = new LinkedList<>();
    MatcherAssert.assertThat(
        "Can't iterate a list with a procedure",
        new AndWithIndex(
            new BiFuncOf<>(
                (text, index) -> list.add(index, text),
                true
            ),
            "hello", "world"
        ),
        new ScalarHasValue<>(
            Matchers.allOf(
                Matchers.equalTo(true),
                new MatcherOf<>(
                    value -> list.size() == 2
                )
            )
        )
    );
}
项目: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)
            )
        )
    );
}
项目:cedato-api-client    文件:SupplyITCase.java   
/**
 * Check supply count.
 * @throws Exception If fails
 * @checkstyle MagicNumberCheck (50 lines)
 */
@Test
public void supplyCount() throws Exception {
    MatcherAssert.assertThat(
        new LengthOf(
            new Auth.Simple(
                System.getProperty("failsafe.cedato.service"),
                System.getProperty("failsafe.cedato.secret")
            )
                .cedato()
                .reports()
                .supplies()
                .extended()
                .supply(
                    Integer.parseInt(
                        System.getProperty("failsafe.cedato.supplyId")
                    )
                )
                .range(
                    LocalDateTime.of(2017, 10, 9, 13, 0, 0)
                                 .atZone(ZoneOffset.UTC),
                    LocalDateTime.of(2017, 10, 9, 13, 59, 59)
                                 .atZone(ZoneOffset.UTC)
                )
                .group("player_hour_subid")
                .limit(10000)
        ).value(),
        CoreMatchers.equalTo(4478)
    );
}
项目:camel    文件:ReadPipeScalarTest.java   
/**
 * ReadPipeScalar can compare itself to a Mapping.
 */
@Test
public void comparesToMapping() {
    final List<YamlLine> lines = new ArrayList<>();
    lines.add(new RtYamlLine("First Line.", 1));
    lines.add(new RtYamlLine("Second Line.", 2));
    lines.add(new RtYamlLine("Third Line.", 3));
    final ReadPipeScalar scalar = 
        new ReadPipeScalar(new RtYamlLines(lines));
    RtYamlMapping map = new RtYamlMapping(
        new HashMap<YamlNode, YamlNode>()
    );
    MatcherAssert.assertThat(scalar.compareTo(map), Matchers.lessThan(0));
}
项目:cactoos    文件:ReversedTextTest.java   
@Test
public void reversedEmptyTextIsEmptyText() {
    MatcherAssert.assertThat(
        "Can't reverse empty text",
        new ReversedText(
            new TextOf("")
        ),
        new TextHasString("")
    );
}
项目:cactoos    文件:MappedTest.java   
@Test
public void transformsEmptyList() {
    MatcherAssert.assertThat(
        "Can't transform an empty iterable",
        new Mapped<String, Text>(
            input -> new UpperText(new TextOf(input)),
            Collections.emptyList()
        ),
        Matchers.emptyIterable()
    );
}
项目:annotation-processor-toolkit    文件:ModelPathResolverTest.java   
@Test
public void getGetter_testDifferentKindOfGetterPrefixes() {

    MatcherAssert.assertThat(ModelPathResolver.getGetter(new GetGetterTestClass(), "isGetter"), Matchers.is("isIsGetter"));
    MatcherAssert.assertThat(ModelPathResolver.getGetter(new GetGetterTestClass(), "getGetter"), Matchers.is("getGetGetter"));
    MatcherAssert.assertThat(ModelPathResolver.getGetter(new GetGetterTestClass(), "hasGetter"), Matchers.is("hasHasGetter"));

}
项目:cactoos    文件:LimitedTest.java   
@Test
public void limitOfZeroProducesEmptyIterable() {
    // @checkstyle MagicNumber (7 lines)
    MatcherAssert.assertThat(
        "Can't limit an iterable to zero items",
        new Limited<>(
            0, new IterableOf<>(0, 1, 2, 3, 4)
        ),
        Matchers.iterableWithSize(0)
    );
}
项目:annotation-processor-toolkit    文件:ElementUtils_CheckModifierOfElementTest.java   
@Test
public void testHasStrictfpModifier() {

    Element e = Mockito.mock(Element.class);
    Mockito.when(e.getModifiers()).thenReturn(Utilities.convertVarargsToSet(Modifier.STRICTFP));
    MatcherAssert.assertThat("Modifier should be found", ElementUtils.CheckModifierOfElement.hasStrictfpModifier(e));

    Mockito.when(e.getModifiers()).thenReturn(Utilities.convertVarargsToSet(Modifier.PRIVATE));
    MatcherAssert.assertThat("Modifier should not be found", !ElementUtils.CheckModifierOfElement.hasStrictfpModifier(e));

    // check null valued element
    MatcherAssert.assertThat("Modifier should not be found for null valued elements", !ElementUtils.CheckModifierOfElement.hasStrictfpModifier(null));

}
项目:cactoos    文件:JoinedTextTest.java   
@Test
public void joinsTexts() throws IOException {
    MatcherAssert.assertThat(
        "Can't join texts",
        new JoinedText(
            new TextOf(" "),
            new TextOf("foo"),
            new TextOf("bar")
        ),
        new TextHasString("foo bar")
    );
}
项目:cactoos    文件:IsBlankTest.java   
@Test
public void determinesBlankText() {
    MatcherAssert.assertThat(
        "Can't determine an empty text with spaces",
        new IsBlank(
            new TextOf("  ")
        ),
        new ScalarHasValue<>(Boolean.TRUE)
    );
}
项目:comdor    文件:LastMentionTestCase.java   
/**
 * Agent already replied once to the last comment.
 * @throws Exception if something goes wrong.
 */
@Test
public void mentionAlreadyReplied() 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());
    comdor.comments().post("@amihaiemil hi there");

    mihai.comments().post("@someoneelse, please check that...");

    try {
        new LastMention(comdor);
        Assert.fail("An IAE should have been thrown!");
    } catch (final MentionLookupException mae) {
        MatcherAssert.assertThat(
            mae.getMessage(),
            Matchers.equalTo("Last mention is already answered!")
        );
    }

}
项目:sunshine    文件:ConfigFromFileTest.java   
@Test
public void hasUnexpected() {
    MatcherAssert.assertThat(
            "Unexpected attribute was loaded",
            !new ConfigFromFile(new ByteArrayInputStream("a =b".getBytes())).has("d")
    );
}
项目:versioneye-api    文件:RtProjectTestCase.java   
/**
 * RtProject can return the ids of its children.
 */
public void returnsChildIds() {
    final Project project = new RtProject(
        new FakeRequest(),
        Mockito.mock(Team.class),
        Json.createObjectBuilder()
            .add(
                "child_ids",
                Json.createArrayBuilder()
                    .add("child1")
                    .add("child2")
                    .build()
            )
            .build()
    );
    MatcherAssert.assertThat(
        project.childIds(),
        Matchers.hasSize(2)
    );
    MatcherAssert.assertThat(
        project.childIds().get(0),
        Matchers.equalTo("child1")
    );
    MatcherAssert.assertThat(
        project.childIds().get(1),
        Matchers.equalTo("child2")
    );
}
项目:keycloak-monitoring-prometheus    文件:MonitoringEventListenerProviderTest.java   
@Test
public void shouldProperlyIncreaseCounterForNormalEvents() throws IOException {
    MonitoringEventListenerProvider listener = new MonitoringEventListenerProvider(tmp.getRoot().getAbsolutePath());
    File existingCounter = new File(tmp.getRoot().getAbsolutePath() + File.separator + "keycloak_events_total;realm=test-realm;type=LOGIN");
    FileUtils.writeStringToFile(existingCounter, "100");

    listener.onEvent(event());

    MatcherAssert.assertThat(FileUtils.readFileToString(existingCounter), Is.is("101"));
}
项目:sunshine    文件:JunitStatusTest.java   
@Test
public void runCount() {
    MatcherAssert.assertThat(
            new JunitStatus(new FakeResult(false, 3, 0, 0)).runCount(),
            Matchers.is(3)
    );
}
项目:jb-hub-client    文件:RtJsonTest.java   
/**
 * RtJson can fetch HTTP request.
 *
 * @throws Exception if there is any problem
 */
@Test
public void sendHttpRequest() throws Exception {
    final MkContainer container = new MkGrizzlyContainer().next(
        new MkAnswer.Simple(HttpURLConnection.HTTP_OK, "{\"body\":\"hi\"}")
    ).start();
    final RtJson json = new RtJson(new ApacheRequest(container.home()));
    MatcherAssert.assertThat(
        json.fetch().getString("body"),
        Matchers.equalTo("hi")
    );
    container.stop();
}
项目:sunshine    文件:LoadableTestNGSuiteTest.java   
@Test
public void testDefaultSuiteDirectoryCreation() throws SuiteException {
    MatcherAssert.assertThat(
            new LoadableTestNGSuite(new SunshineSuite.Fake()).tests(),
            new SuiteFileMatcher()
    );
}
项目:cactoos    文件:AndInThreadsTest.java   
@Test
public void allTrue() throws Exception {
    MatcherAssert.assertThat(
        new AndInThreads(
            new True(),
            new True(),
            new True()
        ).value(),
        Matchers.equalTo(true)
    );
}
项目:sunshine    文件:FileSystemOfJarFileTest.java   
@Test
public void files() throws FileSystemException {
    MatcherAssert.assertThat(
            new FileSystemOfJarFile("build/sample-tests.jar").files(),
            Matchers.hasItem(new FileSystemPathBase("io/github/tatools/testng/Test1.class"))
    );
}
项目:cactoos    文件:IterableOfTest.java   
@Test
public void convertsScalarsToIterable() {
    MatcherAssert.assertThat(
        "Can't convert scalars to iterable",
        new LengthOf(
            new IterableOf<>(
                "a", "b", "c"
            )
        ).intValue(),
        // @checkstyle MagicNumber (1 line)
        Matchers.equalTo(3)
    );
}
项目:cactoos    文件:RepeatedTest.java   
@Test
public void emptyTest() throws Exception {
    MatcherAssert.assertThat(
        "Can't generate an empty iterable",
        new LengthOf(new Repeated<>(0, 0)).intValue(),
        Matchers.equalTo(0)
    );
}
项目:annotation-processor-toolkit    文件:OperationTypeTest.java   
@Test
public void and_doOperation_withValidOperands_FalseAndTrue_Test() {

    Operand operand1 = OperandFactory.createOperationResult(Boolean.class, false);
    Operand operand2 = OperandFactory.createOperationResult(Boolean.class, true);

    Operand result = OperationType.AND.doOperation(operand1, operand2);
    MatcherAssert.assertThat(result.getOperandsJavaType(), Matchers.equalTo((Class) Boolean.class));
    MatcherAssert.assertThat((Boolean) result.value(), Matchers.is(false));

}
项目:cactoos    文件:NumberOfTest.java   
@Test
public void parsesFloat() throws IOException {
    MatcherAssert.assertThat(
        "Can't parse float number",
        new NumberOf("1656.894").floatValue(),
        // @checkstyle MagicNumber (1 line)
        Matchers.equalTo(1656.894F)
    );
}