3

I'm interested in writing a test that allows me to check whether a function returns one of two values. For example:

  @Test
  public void testRandomFunction() {
    assertEquals(
      either(equalTo(2)).or(equalTo(3)),
      RandomFunction(5)
    );
    return;
  }

Reading up online I found out about the matchers in hamcrest. The code compiles but when I run the test, it seems the integer 5 is compared to a matcher object instead of integers 2 and 3.

I am open to try something different besides matchers if it makes this easier. Does anyone know how I can do this?

I have also tried the following without success:

   @Test
  public void testRandomFunction() {
    Set<Integer> acceptedValues = new HashSet<Integer>();
    acceptedValues.add(2);
    acceptedValues.add(3);

    assertEquals(
      isIn(acceptedValues),
      RandomFunction(5)
    );
    return;
  }
RodCardenas
  • 585
  • 6
  • 14

2 Answers2

3

To use the matchers, you need to use assertThat instead of assertEquals.

assertThat(
    "RandomFunction result",
    RandomFunction(5),
    either(equalTo(2)).or(equalTo(3)),
);
1
@Test
public void testRandomFunction() {
  int result = randomFunction(5);
  assertTrue(result == 2 || result == 3);
}
Tiago Bértolo
  • 3,874
  • 3
  • 35
  • 53