user1907849
user1907849

Reputation: 990

Running testcases in golang during exception

I am writing testcases for method with doesnt return any values , for eg:

func GetByNameReturnNull(serName string)
{
 //Logic
}

My testcasefile is myTest.go which has two parameters , one calling the method with invalid input and calling the method with valid input.

func Test1(t *testing.T) { 
    GetByNameReturnNull("Invalid")
}


func Test2(t *testing.T) { 

    GetByNameReturnNull("valid")
}

So , the first testcase will fail and throw the exception , I cant handle it in the conventional way like ,

"check for err from the returned method because the method doesnt return anything at all. When I execute the command,

$go test ./... -v

the second testcase will not execute because of the exception of the first.

So Without changing any logic in the base method(GetByNameReturnNull) to return err or anything , is there any way to handle this scenario in the testcase file itself to print

1 fail 1 pass in the output?

Upvotes: 1

Views: 487

Answers (2)

OneOfOne
OneOfOne

Reputation: 99244

@VonC is correct, there's no way to automatically handle it, however you can simply make a wrapper and call it in each test.

This way you don't have to use a global variable to keep track of the tests.

Example:

func logPanic(t *testing.T, f func()) {
    defer func() {
        if err := recover(); err != nil {
            t.Errorf("paniced: %v", err)
        }
    }()
    f()
}

func Test1(t *testing.T) {
    logPanic(t, func() {
        GetByNameReturnNull("invalid")
    })
    //or if the function doesn't take arguments
    //logPanic(t, GetByNameReturnNull)
}

func Test2(t *testing.T) {
    logPanic(t, func() {
        GetByNameReturnNull("valid")
    })
}

Upvotes: 4

VonC
VonC

Reputation: 1324547

You shouldn't see "1 fail", if you expect your test to panic.
You should see both tests succeed.

Instead, you should test specifically the panic case, as described, for instance, in "Understanding Defer, Panic and Recover ":

func TestPanic(t *testing.T) error {
    defer func() {
        fmt.Println("Start Panic Defer")
        if r := recover(); r != nil {
            fmt.Println("Defer Panic:", r)
        } else {
            t.Error("Should have panicked!")
        }
    }()

    fmt.Println("Start Test")
    panic("Mimic Panic")
}

That test would pass if you call a function which exits with a panic.

Upvotes: 3

Related Questions