Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit assert, value is between two integers

Tags:

java

random

junit

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.

like image 768
DanMc Avatar asked Jan 30 '13 22:01

DanMc


People also ask

How do you use assertTrue in JUnit?

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.

How do you find the assert value of Boolean?

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).

What is assert assertSame?

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.


2 Answers

@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);
}
like image 137
Simulant Avatar answered Sep 18 '22 20:09

Simulant


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)));
}
like image 30
feilong Avatar answered Sep 20 '22 20:09

feilong