Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit assert OR condition in my test case

In my test case, I get an integer value:

int val = getXXX();

Then, I would like to check if val either equals to 3 or equals to 5 which is OK in either case. So, I did:

assertTrue(val == 3 || val==5);

I run my test, the log shows val is 5, but my above assertion code failed with AssertionFailedError. Seems I can not use assertTrue(...) in this way, then, how to check true for OR condition?

like image 643
Leem.fin Avatar asked Sep 25 '13 12:09

Leem.fin


People also ask

How do I add assert in JUnit?

String obj1="Junit"; String obj2="Junit"; assertEquals(obj1,obj2); Above assert statement will return true as obj1. equals(obj2) returns true.

What does assertFalse mean in JUnit?

In assertFalse, you are asserting that an expression evaluates to false. If it is not, then the message is displayed and the assertion fails. assertTrue (message, value == false) == assertFalse (message, value); These are functionally the same, but if you are expecting a value to be false then use assertFalse .

What does assert assertEquals return?

assertEquals. Asserts that two objects are equal. If they are not, an AssertionError without a message is thrown. If expected and actual are null , they are considered equal.


3 Answers

You can use Hamcrest matchers to get a clearer error message here:

int i = 2;
assertThat(i, Matchers.either(Matchers.is(3)).or(Matchers.is(5))

or

int i = 2;
assertThat(i, Matchers.anyOf(Matchers.is(3),Matchers.is(5)));

This will more clearly explain:

Expected: (is <3> or is <5>)
     but: was <2>

showing exactly the expectation and the incorrect value that was provided.

like image 88
Joe Avatar answered Oct 22 '22 08:10

Joe


ive tried to write quick test:

@Test
public void testName() {
    int i = 5;
    junit.framework.Assert.assertTrue(i == 3 || i == 5);

}

its passing always so i guess there is some inbetween code when your value is changed. You can use

org.junit.Assert.assertEquals(5, i);

to check value - this assertion will print out nice info whats wrong, for example:

java.lang.AssertionError: 
Expected :4
Actual   :5
like image 33
smajlo Avatar answered Oct 22 '22 08:10

smajlo


While Harmcrest matchers can do the job, these constants can be easily refactored to a more meaninful constant, like a list of valid values. Then you can use the contains method to check that the value is present in the list - IMO is also easier to read:

public class Foo {
    public static final List<Integer> VALID_VALUES = Arrays.asList(3, 5);
}

@Test
public void testName() {
    int i = 5;
    Assert.assertTrue(Foo.VALID_VALUES.contains(i));
}
like image 4
A. Rodas Avatar answered Oct 22 '22 07:10

A. Rodas