I need to write a JUnit test for an algorithm I wrote that outputs a random integer between two known values.
I need a JUnit test (I.e. an assertEquals like test) that asserts that the out-putted value is between these two integers (or not).
I.e. I have the values 5 and 10, the output would be a random value between 5 and 10. If the test is positive the number was between the two values, otherwise it was not.
assertTrue() If you wish to pass the parameter value as True for a specific condition invoked in a method, then you can make use of the. JUnit assertTrue(). You can make use of JUnit assertTrue() in two practical scenarios. By passing condition as a boolean parameter used to assert in JUnit with the assertTrue method.
You can test objects assertEquals(a,b) and assertTrue(a. equals(b)) or assertTrue(a==b) (for primitives). In this case of course assertEquals(a,b) is the only possible variant. It is null safe and more informative in case of test fault (you get exact fault not true or false).
assertEquals: Asserts that two objects are equal. assertSame: Asserts that two objects refer to the same object. In other words. assertEquals: uses the equals() method, or if no equals() method was overridden, compares the reference between the 2 objects.
@Test
public void randomTest(){
int random = randomFunction();
int high = 10;
int low = 5;
assertTrue("Error, random is too high", high >= random);
assertTrue("Error, random is too low", low <= random);
//System.out.println("Test passed: " + random + " is within " + high + " and + low);
}
you can use junit assertThat
method (since JUnit 4.4
)
see http://www.vogella.com/tutorials/Hamcrest/article.html
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertThat;
......
@Test
public void randomTest(){
int random = 8;
int high = 10;
int low = 5;
assertThat(random, allOf(greaterThan(low), lessThan(high)));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With