Search code examples
javaunit-testingjunitparameterized

How can i check if a variable is inside a range of numbers in a parameterized JUnit Test


I am creating a worksheet about language models for a course called "Information Retrieval". The students should be able to check if their code produces the correct answers so i set up a couple of Junit Tests which checks a number of cases. Because i wanted to include multiple test-cases i decided to use parameterized Junit Tests. (I followed this example: http://www.mkyong.com/unittest/junit-4-tutorial-6-parameterized-test/) I want to test a function which returns a float which can be within a range of numbers. If I would be testing two floats i would be able to use

assertEquals(float expected, float actual, float delta)

where the delta is the range. But because I am using parameterized Tests I have to work with Objects

assertEquals(Object expected, Object actual)

These Objects are Lists which contain Floats, but in the Code they are just Objects so Solutions like these do not work:

assertEquals(Object expected, Object actual, float delta) (this method does not exist)

assertTrue(Math.abs(Object expected - Object actual)<ERROR_MARGIN) (Operator '-' undefined for Object)


Solution

  • You could write your own method that does the comparison, and have that return true or false

    assertTrue(objectsAreInRange(actual, expected, delta));
    
    boolean objectsAreInRange(Object actual, Object expected, float delta){
    ...
    }