jeudi 8 août 2019

How to test function without duplication?

I have a function (main) which calls other functions(sub). I've written unit tests for sub functions and now want to write a unit test for main function. The question is how do I test main function without duplicating logic for sub functions and assuming their logic in main function test(e.g. mocking calls to DB in them).

Here is an example:


type A struct {
    db DB
}

func (a *A) m(i int) bool {
    if a.s1(i) {
        return false
    }

    if a.s2(i) {
        return false
    }

    if i % 2 == 0 {
        return false
    }

    return true
}

func (a *A) s1(i int) bool {
    // some condition check with DB call here
    return true
}

func (a *A) s2(i int) bool {
    // some condition check with DB call here
    return true
}

And example testing code(don't check correctness, it's example):


func TestS1(t *testing.T) {
    m := &mockDB{}
    m.On("Check", 5).Return(true)
    a := &A{db: m}
    res := a.s1(5)
    if res == true {
        t.Error("got true")
    }
}

func TestS2(t *testing.T) {
    m := &mockDB{}
    m.On("Exists", 5).Return(true)
    a := &A{db: m}
    res := a.s1(5)
    if res == true {
        t.Error("got true")
    }
}

func TestM(t *testing.T) {
    m := &mockDB{}
    // how do i remove this duplication?
    m.On("Check", 5).Return(true)
    m.On("Exists", 5).Return(true)
    a := &A{db: m}
    res := a.m(5)
    if res == true {
        t.Error("got true")
    }
}

Aucun commentaire:

Enregistrer un commentaire