0

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.

2
  • Since your Builder() function return error along with the object, you should first make sure the Err is nil, before asserting anything else. Expect(err).To(BeNil()) Expect(testInstance.List).To(HaveLen(1)) Commented May 2, 2020 at 4:51
  • Thanks @Sheshnath, but even when this prevents the panic (and this is a huge improvement in the legibility of the test output, still I have to repeat the test on each It. I was wondering if there was a way for establishing a dependency or hierarchy between assertions (maybe by using contexts) so that a "higher" level assertion if not satisfied, prevents all other "lower-level" or "dependant" assertions not to be exectued at all. Commented May 4, 2020 at 20:04

1 Answer 1

0

According to ginkgo's documentation

It is also common to place assertions within BeforeEach and AfterEach blocks. These assertions can, for example, assert that no errors occurred while preparing the state for the spec.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.