dimanche 30 octobre 2016

Are there any existing libraries for side-by-side testing of java methods? [on hold]

I'm refactoring an old utility class, and I want to make sure I haven't broken the method contract at all. To that end, I'm trying to call both methods with identical inputs (generated by QuickCheck) and compare both the resulting output, but any side-effects applied to the input, or exceptions thrown.

The code to do this for each method would be quite a bit to copy-paste, and I'm sure it can be done "better" with a reflection-based utility utilising mocks and/or spies.

import java.util.Date;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

...

@Property
public void testDateAdd(
        Date date,
        Integer amount,
        @InRange(minInt = 0, maxInt = 15) Integer field

) throws Exception {

    final Date date1 = new Date(date.getTime());
    final Integer amount1 = new Integer(amount);
    final Integer field1 = new Integer(field1);
    Date result1 = null;
    Exception error1 = null;

    try {
        result1 = DateFunctionsOriginal.dateAdd(date1, amount1, field1);

    } catch (Exception error) {
        error1 = error;
    }

    final Date date2 = new Date(date.getTime());
    final Integer amount2 = new Integer(amount);
    final Integer field2 = new Integer(field1);
    Date result2 = null;
    Exception error2 = null;

    try {
        result2 = DateFunctions.dateAdd(date2, amount2, field2);

    } catch (Exception error) {
        error2 = error;
    }

    assertThat(date1, is(equalTo(date2)));
    assertThat(amount1, is(equalTo(amount2)));
    assertThat(field1, is(equalTo(field2)));
    assertThat(error1, error2 == null ? is(nullValue()) : isA(error2.getClass()));
    assertThat(result1, is(equalTo(result2)));

}

Not perfect, but that's what I'm looking at for all 200 or so methods, and while I love a good challenge, I'd like to avoid 'rolling my own' if I can help it.





Aucun commentaire:

Enregistrer un commentaire