Java Code Examples for org.hamcrest.MatcherAssert

The following are top voted examples for showing how to use org.hamcrest.MatcherAssert. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: VKMusicUploader   File: WallPostFromGroupTest.java   View source code 6 votes vote down vote up
@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")
        )
    );
}
 
Example 2
Project: cactoos   File: SkippedTest.java   View source code 6 votes vote down vote up
@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"
        )
    );
}
 
Example 3
Project: cactoos   File: MapOfTest.java   View source code 6 votes vote down vote up
@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)
    );
}
 
Example 4
Project: cactoos   File: ResourceOfTest.java   View source code 6 votes vote down vote up
@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,
            }
        )
    );
}
 
Example 5
Project: camel   File: ScalarTest.java   View source code 6 votes vote down vote up
/**
 * 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)
    );
}
 
Example 6
Project: Android-Migrator   File: MigrationFileAssetTest.java   View source code 6 votes vote down vote up
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)
    );
}
 
Example 7
Project: cactoos   File: BytesOfTest.java   View source code 6 votes vote down vote up
@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("друг!")
        )
    );
}
 
Example 8
Project: comdor   File: ConfusedTestCase.java   View source code 6 votes vote down vote up
/**
 * 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)
    );

}
 
Example 9
Project: cactoos   File: AsyncFuncTest.java   View source code 6 votes vote down vote up
@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)
        )
    );
}
 
Example 10
Project: versioneye-api   File: RepositoriesPageTestCase.java   View source code 6 votes vote down vote up
/**
 * 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")
    );   
}
 
Example 11
Project: cactoos   File: PartitionedTest.java   View source code 6 votes vote down vote up
@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)
            )
        )
    );
}
 
Example 12
Project: polymorphia   File: TestEnums.java   View source code 6 votes vote down vote up
@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));

}
 
Example 13
Project: cactoos   File: BytesOfTest.java   View source code 6 votes vote down vote up
@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("товарищ!")
        )
    );
}
 
Example 14
Project: annotation-processor-toolkit   File: ElementUtils_AccessEnclosingElementsTest.java   View source code 6 votes vote down vote up
@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)));


}
 
Example 15
Project: cactoos   File: StickyMapTest.java   View source code 6 votes vote down vote up
@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())
    );
}
 
Example 16
Project: camel   File: RtYamlMappingTest.java   View source code 6 votes vote down vote up
/**
 * 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()
    );
}
 
Example 17
Project: cactoos   File: AndWithIndexTest.java   View source code 6 votes vote down vote up
@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
                )
            )
        )
    );
}
 
Example 18
Project: cactoos   File: DateOfTest.java   View source code 6 votes vote down vote up
@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)
            )
        )
    );
}
 
Example 19
Project: cedato-api-client   File: SupplyITCase.java   View source code 5 votes vote down vote up
/**
 * 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)
    );
}
 
Example 20
Project: camel   File: ReadPipeScalarTest.java   View source code 5 votes vote down vote up
/**
 * 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));
}
 
Example 21
Project: cactoos   File: ReversedTextTest.java   View source code 5 votes vote down vote up
@Test
public void reversedEmptyTextIsEmptyText() {
    MatcherAssert.assertThat(
        "Can't reverse empty text",
        new ReversedText(
            new TextOf("")
        ),
        new TextHasString("")
    );
}
 
Example 22
Project: cactoos   File: MappedTest.java   View source code 5 votes vote down vote up
@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()
    );
}
 
Example 23
Project: annotation-processor-toolkit   File: ModelPathResolverTest.java   View source code 5 votes vote down vote up
@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"));

}
 
Example 24
Project: cactoos   File: LimitedTest.java   View source code 5 votes vote down vote up
@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)
    );
}
 
Example 25
Project: annotation-processor-toolkit   File: ElementUtils_CheckModifierOfElementTest.java   View source code 5 votes vote down vote up
@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));

}
 
Example 26
Project: cactoos   File: JoinedTextTest.java   View source code 5 votes vote down vote up
@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")
    );
}
 
Example 27
Project: cactoos   File: IsBlankTest.java   View source code 5 votes vote down vote up
@Test
public void determinesBlankText() {
    MatcherAssert.assertThat(
        "Can't determine an empty text with spaces",
        new IsBlank(
            new TextOf("  ")
        ),
        new ScalarHasValue<>(Boolean.TRUE)
    );
}
 
Example 28
Project: comdor   File: LastMentionTestCase.java   View source code 5 votes vote down vote up
/**
 * 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!")
        );
    }

}
 
Example 29
Project: sunshine   File: ConfigFromFileTest.java   View source code 5 votes vote down vote up
@Test
public void hasUnexpected() {
    MatcherAssert.assertThat(
            "Unexpected attribute was loaded",
            !new ConfigFromFile(new ByteArrayInputStream("a =b".getBytes())).has("d")
    );
}
 
Example 30
Project: versioneye-api   File: RtProjectTestCase.java   View source code 5 votes vote down vote up
/**
 * 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")
    );
}
 
Example 31
Project: keycloak-monitoring-prometheus   File: MonitoringEventListenerProviderTest.java   View source code 5 votes vote down vote up
@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"));
}
 
Example 32
Project: sunshine   File: JunitStatusTest.java   View source code 5 votes vote down vote up
@Test
public void runCount() {
    MatcherAssert.assertThat(
            new JunitStatus(new FakeResult(false, 3, 0, 0)).runCount(),
            Matchers.is(3)
    );
}
 
Example 33
Project: jb-hub-client   File: RtJsonTest.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 34
Project: sunshine   File: LoadableTestNGSuiteTest.java   View source code 5 votes vote down vote up
@Test
public void testDefaultSuiteDirectoryCreation() throws SuiteException {
    MatcherAssert.assertThat(
            new LoadableTestNGSuite(new SunshineSuite.Fake()).tests(),
            new SuiteFileMatcher()
    );
}
 
Example 35
Project: cactoos   File: AndInThreadsTest.java   View source code 5 votes vote down vote up
@Test
public void allTrue() throws Exception {
    MatcherAssert.assertThat(
        new AndInThreads(
            new True(),
            new True(),
            new True()
        ).value(),
        Matchers.equalTo(true)
    );
}
 
Example 36
Project: sunshine   File: FileSystemOfJarFileTest.java   View source code 5 votes vote down vote up
@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"))
    );
}
 
Example 37
Project: cactoos   File: IterableOfTest.java   View source code 5 votes vote down vote up
@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)
    );
}
 
Example 38
Project: cactoos   File: RepeatedTest.java   View source code 5 votes vote down vote up
@Test
public void emptyTest() throws Exception {
    MatcherAssert.assertThat(
        "Can't generate an empty iterable",
        new LengthOf(new Repeated<>(0, 0)).intValue(),
        Matchers.equalTo(0)
    );
}
 
Example 39
Project: annotation-processor-toolkit   File: OperationTypeTest.java   View source code 5 votes vote down vote up
@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));

}
 
Example 40
Project: cactoos   File: NumberOfTest.java   View source code 5 votes vote down vote up
@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)
    );
}