Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using random value in a JUnit test class [closed]

Is it a good pratice to use random value to create a test object with JUnit ? Like this :

public class MonomialTest {

    private static final Random RANDOM = new Random();

    private Monomial monomial;
    private float coefficient;
    private int exponent;

    @Before
    public void setUp() throws Exception {
        coefficient = RANDOM.nextFloat();
        exponent = RANDOM.nextInt();
        monomial = new Monomial(coefficient, exponent);
    }

    @Test
    ...
    ...
    ...

}

Or should I use fixed values ?

like image 340
dblouis Avatar asked Oct 30 '22 10:10

dblouis


2 Answers

Unit tests should be deterministic to simplify finding the fault when a test fails. Therefore they should not include random values.

Checking that certain properties hold for arbitrary values (which your tests effectively do) does make sense though: For that you can use property-based testing frameworks such as junit-quickcheck which will do the random data generation for you.

like image 200
avandeursen Avatar answered Nov 08 '22 04:11

avandeursen


it's okay to use random, but to make sure that it's working well: print the random value so u can see it, and make sure that the result is what expected to be.

or just put a known value instead of a random one.

like image 26
Duha Avatar answered Nov 08 '22 04:11

Duha