Comprensione dei test basati sulle proprietà

-2

Sto leggendo sui test basati su proprietà e mi chiedo come posso testare questo codice usando quel paradigma.

class Invoice {

    private final String id;
    private final String companyName;

    public String name() {
        return id + "_" + removeDots(companyName.trim());
    }

}

Voglio testare il metodo Invoice::name , quindi vorrei fare qualcosa del genere:

class InvoiceTest {

    //Let's say 'id' and 'companyName' are random auto-generated values
    //by some framework
    @Test 
    public void nameTest(String id, String companyName) {
        Invoice invoice = new Invoice(id, companyName);
        assertThat(invoice.name()).isEqualTo(id + "_" + removeDots(companyName.trim()));
    }

}

Come vedi, non ha senso. Sto reimplementando la logica nel metodo di test. Forse, è un test basato sulle proprietà adatto solo per la logica "matematica"?

    
posta Héctor 15.11.2018 - 17:53
fonte

1 risposta

2

Maybe, is property based testing suitable only for "mathematical" logic?

Non necessariamente.

Writing tests first forces you to think about the problem you're solving. Writing property-based tests forces you to think way harder. -- Jessica Kerr

boolean hasDots(String candidate) { ... }

@Test
public void it_removes_the_dots(String anyCompanyName) {
    String id = "0";
    Invoice invoice = new Invoice(id, anyCompanyName);
    String name = invoice.name();

    assertFalse( hasDots(name) );
}

@Test
public void it_leaves_the_same_when_no_dots(String anyCompanyNameWithoutDots) {
    assume ! hasDots(anyCompanyNameWithoutDots);

    String id = "0";
    Invoice invoice = new Invoice(id, anyCompanyNameWithoutDots);
    String invoiceName = invoice.name()

    assertTrue(invoiceName.endsWith(anyCompanyNameWithoutDots));
}

@Test
public void it_prepends_the_identifier_without_changing_it(String anyIdentifier) {
    String companyName = "BobsBoringBusiness";
    Invoice invoice = new Invoice(anyIdentifier, companyName );
    String invoiceName = invoice.name()

    assertTrue(invoiceName.startsWith(anyIdentifier));
}


@Test
public void it_prepends_the_identifier_without_removing_dots(String anyIdentifierWithDots) {
    assume hasDots(anyIdentifierWithDots);

    String companyName = "BobsBoringBusiness";
    Invoice invoice = new Invoice(anyIdentifierWithDots, companyName );
    String invoiceName = invoice.name()

    assertTrue(invoiceName.startsWith(anyIdentifierWithDots));
}
// ... and so on.
    
risposta data 15.11.2018 - 19:31
fonte

Leggi altre domande sui tag