vendredi 1 mai 2020

Correct way to check for non null values in ginkgo test

Suppose a function Builder that returns a struct like this:

type MyStruct struct{
      List  []OtherStruct

 }

I want to test the Builder function using ginkgo. I created a test suite with the following structure:

Describe("Builder Test", func() {
    var (
       testInstance Mystruct
       err error
    )

    BeforeEach(func(){
        testInstance, err = Builder()
    })

    It("Should not fail", func(){
       Expect(err).NotTo(HaveOccurred())
    })

    It("Should have a valid List", func(){
       Expect(testInstance.List).To(HaveLen(1))
    })

    It("Should pass some tests", func(){
       Expect(testInstance.List).To(SomeCheck())
    })

    It("Should pass other tests", func(){
       Expect(testInstance.List).To(OtherCheck())
    })

    It("Should pass yet nother tests", func(){
       Expect(testInstance.List).To(YetSomeCheck())
    })

})

However, if for some reason the Builder fails to initialize the testInstance correctly and the List field is not initialized, all the It tests fail with a Panic due to index out of bounds. As I expect the number of tests to grow, I would like to prevent this to happen. I added the 'It'("Should have a valid List")assertion, but this doesnt prevent the otherIt` to be executed and fail.

I'm wonderting if there is an idiomatic way to add a check for testInstance.List to be valid before the It clauses that use it are executed.

Aucun commentaire:

Enregistrer un commentaire