JavaHamcrest icon indicating copy to clipboard operation
JavaHamcrest copied to clipboard

Casted Type should not matter for containsInAnyOrder

Open thigg opened this issue 5 years ago • 4 comments

Regard following Example:

import java.util.Arrays;

import org.hamcrest.Matchers;
import org.hamcrest.core.AnyOf;
import org.junit.Test;

import static org.junit.Assert.assertThat;


public class TestHamcrest {
    @Test
    public void hamcrestTest() {
        new AnyOf<>(null, null);
        String[] truth = new String[]{"1", "2"};
        assertThat(Arrays.asList("1", "2"), Matchers.containsInAnyOrder(truth));
        Object otherTruth = truth;
        assertThat(Arrays.asList("1", "2"), Matchers.containsInAnyOrder(otherTruth));
    }
}

Result:

java.lang.AssertionError: 
Expected: iterable over [["1", "2"]] in any order
     but: Not matched: "1"

	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
	at org.junit.Assert.assertThat(Assert.java:956)
	at org.junit.Assert.assertThat(Assert.java:923)
	at or.example.Example.hamcrestTest(Example.java:22)

The first assert is successfull the second isn't. This leads to very subtle bugs.

Affected: Version: junit:4.12 with hamcrest:1.3 (java-8-openjdk) and Version: junit:4.12 with hamcrest:2.2 (1.3 excluded) (java-13-openjdk)

Actual Behavior: If an array is casted to an object, containsInAnyOrder (and most probably others) regards it as a single item. Thus it asserts that the array ["1","2"] is in the results.

Expected Behavior: Both calls should behave the same.

thigg avatar May 02 '20 14:05 thigg

@thigg please retest with org.hamcrest:hamcrest:2.2 as we have no plans to do any 1.x releases.

nhojpatrick avatar May 04 '20 14:05 nhojpatrick

Still valid in 2.2. Updated first comment. Confirmed correct version via:

     <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.hamcrest</groupId>
                    <artifactId>hamcrest-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest</artifactId>
            <version>2.2</version>
            <scope>test</scope>
        </dependency>

(confirmed with dependency:tree)

and new AnyOf<>(null, null); which is a 2.2 feature according to https://github.com/hamcrest/JavaHamcrest/pull/245

thigg avatar May 05 '20 09:05 thigg

@nhojpatrick could you please review #317

gokareless avatar Sep 06 '20 09:09 gokareless

@ anyone?

gokareless avatar Feb 12 '21 20:02 gokareless