Testing lifecyle in Go. Is it possible to add tear up and down method without duplication of code?











up vote
0
down vote

favorite












I started working with Go a month go. I come from java/kotlin background and I would like to understand if it's possible to achieve some of the same stuff that I did in those languages even in Go.



My current problem is this one.



I have a set of integration test cases where I need to initialize some stuff and then clean the resources: a common use case, I believe.



Here's some pseudo code of what I want achieve, if possible:



for each test {
init resources
run test {
init test resources
execute method under test
assert
}
clean resources
}


At the moment, what I could try, was this approach:



func TestMain(m *testing.M) {
setup()
code := m.Run()
shutdown()
os.Exit(code)
}


Which is fine generally speaking if not that it runs at package level. That doesn't give me much control at the moment because I would like to run one of those per test files. (that's what I noticed at least, please let me know if I'm wrong about it)



At the moment what I'm doing is basically run initialization for each test, but that's really a lot of duplicated code:



address, tearDownTestCase := testutils.SetupTestCase(emptyContext, postRouter(login.LoginUser), "/login")
defer tearDownTestCase()
// init test use case data
// run test
// clean use case data


Do you think there is a better approach?










share|improve this question






















  • testify github.com/stretchr/testify has a fixture system
    – Vorsprung
    yesterday






  • 2




    Your current approach is idiomatic. If the setup really is the same for all tests, consider table driven test.
    – Peter
    yesterday










  • @Peter yes, it's the same for all test but table driven approach doesn't allow me to express what's the test is about. If I can keep single tests I'll have the test name that describes it. Especially in integration tests where more things happen under the hood, I prefer keeping the tests separated.
    – dierre
    14 hours ago










  • Go has subtests for descriptive related names.
    – Peter
    14 hours ago















up vote
0
down vote

favorite












I started working with Go a month go. I come from java/kotlin background and I would like to understand if it's possible to achieve some of the same stuff that I did in those languages even in Go.



My current problem is this one.



I have a set of integration test cases where I need to initialize some stuff and then clean the resources: a common use case, I believe.



Here's some pseudo code of what I want achieve, if possible:



for each test {
init resources
run test {
init test resources
execute method under test
assert
}
clean resources
}


At the moment, what I could try, was this approach:



func TestMain(m *testing.M) {
setup()
code := m.Run()
shutdown()
os.Exit(code)
}


Which is fine generally speaking if not that it runs at package level. That doesn't give me much control at the moment because I would like to run one of those per test files. (that's what I noticed at least, please let me know if I'm wrong about it)



At the moment what I'm doing is basically run initialization for each test, but that's really a lot of duplicated code:



address, tearDownTestCase := testutils.SetupTestCase(emptyContext, postRouter(login.LoginUser), "/login")
defer tearDownTestCase()
// init test use case data
// run test
// clean use case data


Do you think there is a better approach?










share|improve this question






















  • testify github.com/stretchr/testify has a fixture system
    – Vorsprung
    yesterday






  • 2




    Your current approach is idiomatic. If the setup really is the same for all tests, consider table driven test.
    – Peter
    yesterday










  • @Peter yes, it's the same for all test but table driven approach doesn't allow me to express what's the test is about. If I can keep single tests I'll have the test name that describes it. Especially in integration tests where more things happen under the hood, I prefer keeping the tests separated.
    – dierre
    14 hours ago










  • Go has subtests for descriptive related names.
    – Peter
    14 hours ago













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I started working with Go a month go. I come from java/kotlin background and I would like to understand if it's possible to achieve some of the same stuff that I did in those languages even in Go.



My current problem is this one.



I have a set of integration test cases where I need to initialize some stuff and then clean the resources: a common use case, I believe.



Here's some pseudo code of what I want achieve, if possible:



for each test {
init resources
run test {
init test resources
execute method under test
assert
}
clean resources
}


At the moment, what I could try, was this approach:



func TestMain(m *testing.M) {
setup()
code := m.Run()
shutdown()
os.Exit(code)
}


Which is fine generally speaking if not that it runs at package level. That doesn't give me much control at the moment because I would like to run one of those per test files. (that's what I noticed at least, please let me know if I'm wrong about it)



At the moment what I'm doing is basically run initialization for each test, but that's really a lot of duplicated code:



address, tearDownTestCase := testutils.SetupTestCase(emptyContext, postRouter(login.LoginUser), "/login")
defer tearDownTestCase()
// init test use case data
// run test
// clean use case data


Do you think there is a better approach?










share|improve this question













I started working with Go a month go. I come from java/kotlin background and I would like to understand if it's possible to achieve some of the same stuff that I did in those languages even in Go.



My current problem is this one.



I have a set of integration test cases where I need to initialize some stuff and then clean the resources: a common use case, I believe.



Here's some pseudo code of what I want achieve, if possible:



for each test {
init resources
run test {
init test resources
execute method under test
assert
}
clean resources
}


At the moment, what I could try, was this approach:



func TestMain(m *testing.M) {
setup()
code := m.Run()
shutdown()
os.Exit(code)
}


Which is fine generally speaking if not that it runs at package level. That doesn't give me much control at the moment because I would like to run one of those per test files. (that's what I noticed at least, please let me know if I'm wrong about it)



At the moment what I'm doing is basically run initialization for each test, but that's really a lot of duplicated code:



address, tearDownTestCase := testutils.SetupTestCase(emptyContext, postRouter(login.LoginUser), "/login")
defer tearDownTestCase()
// init test use case data
// run test
// clean use case data


Do you think there is a better approach?







go testing






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked yesterday









dierre

4,4461059103




4,4461059103












  • testify github.com/stretchr/testify has a fixture system
    – Vorsprung
    yesterday






  • 2




    Your current approach is idiomatic. If the setup really is the same for all tests, consider table driven test.
    – Peter
    yesterday










  • @Peter yes, it's the same for all test but table driven approach doesn't allow me to express what's the test is about. If I can keep single tests I'll have the test name that describes it. Especially in integration tests where more things happen under the hood, I prefer keeping the tests separated.
    – dierre
    14 hours ago










  • Go has subtests for descriptive related names.
    – Peter
    14 hours ago


















  • testify github.com/stretchr/testify has a fixture system
    – Vorsprung
    yesterday






  • 2




    Your current approach is idiomatic. If the setup really is the same for all tests, consider table driven test.
    – Peter
    yesterday










  • @Peter yes, it's the same for all test but table driven approach doesn't allow me to express what's the test is about. If I can keep single tests I'll have the test name that describes it. Especially in integration tests where more things happen under the hood, I prefer keeping the tests separated.
    – dierre
    14 hours ago










  • Go has subtests for descriptive related names.
    – Peter
    14 hours ago
















testify github.com/stretchr/testify has a fixture system
– Vorsprung
yesterday




testify github.com/stretchr/testify has a fixture system
– Vorsprung
yesterday




2




2




Your current approach is idiomatic. If the setup really is the same for all tests, consider table driven test.
– Peter
yesterday




Your current approach is idiomatic. If the setup really is the same for all tests, consider table driven test.
– Peter
yesterday












@Peter yes, it's the same for all test but table driven approach doesn't allow me to express what's the test is about. If I can keep single tests I'll have the test name that describes it. Especially in integration tests where more things happen under the hood, I prefer keeping the tests separated.
– dierre
14 hours ago




@Peter yes, it's the same for all test but table driven approach doesn't allow me to express what's the test is about. If I can keep single tests I'll have the test name that describes it. Especially in integration tests where more things happen under the hood, I prefer keeping the tests separated.
– dierre
14 hours ago












Go has subtests for descriptive related names.
– Peter
14 hours ago




Go has subtests for descriptive related names.
– Peter
14 hours ago












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










Go does not have the inbuilt functionality to support tear up and down methods. However, there are multiple third-party packages that enable this. Out of all of these, I like the ginkgo package the most. It is very expressive and avoids code duplication.



A sample test would look like



var _ = Describe("Book", func() {
var (
longBook Book
shortBook Book
)

BeforeEach(func() {
longBook = Book{
Title: "Les Miserables",
Author: "Victor Hugo",
Pages: 1488,
}

shortBook = Book{
Title: "Fox In Socks",
Author: "Dr. Seuss",
Pages: 24,
}
})

Describe("Categorizing book length", func() {
Context("With more than 300 pages", func() {
It("should be a novel", func() {
Expect(longBook.CategoryByLength()).To(Equal("NOVEL"))
})
})

Context("With fewer than 300 pages", func() {
It("should be a short story", func() {
Expect(shortBook.CategoryByLength()).To(Equal("SHORT STORY"))
})
})
})
})


Similarity there are other lifecycle methods like afterEach, justBeforeEach etc.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53238373%2ftesting-lifecyle-in-go-is-it-possible-to-add-tear-up-and-down-method-without-du%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    Go does not have the inbuilt functionality to support tear up and down methods. However, there are multiple third-party packages that enable this. Out of all of these, I like the ginkgo package the most. It is very expressive and avoids code duplication.



    A sample test would look like



    var _ = Describe("Book", func() {
    var (
    longBook Book
    shortBook Book
    )

    BeforeEach(func() {
    longBook = Book{
    Title: "Les Miserables",
    Author: "Victor Hugo",
    Pages: 1488,
    }

    shortBook = Book{
    Title: "Fox In Socks",
    Author: "Dr. Seuss",
    Pages: 24,
    }
    })

    Describe("Categorizing book length", func() {
    Context("With more than 300 pages", func() {
    It("should be a novel", func() {
    Expect(longBook.CategoryByLength()).To(Equal("NOVEL"))
    })
    })

    Context("With fewer than 300 pages", func() {
    It("should be a short story", func() {
    Expect(shortBook.CategoryByLength()).To(Equal("SHORT STORY"))
    })
    })
    })
    })


    Similarity there are other lifecycle methods like afterEach, justBeforeEach etc.






    share|improve this answer

























      up vote
      1
      down vote



      accepted










      Go does not have the inbuilt functionality to support tear up and down methods. However, there are multiple third-party packages that enable this. Out of all of these, I like the ginkgo package the most. It is very expressive and avoids code duplication.



      A sample test would look like



      var _ = Describe("Book", func() {
      var (
      longBook Book
      shortBook Book
      )

      BeforeEach(func() {
      longBook = Book{
      Title: "Les Miserables",
      Author: "Victor Hugo",
      Pages: 1488,
      }

      shortBook = Book{
      Title: "Fox In Socks",
      Author: "Dr. Seuss",
      Pages: 24,
      }
      })

      Describe("Categorizing book length", func() {
      Context("With more than 300 pages", func() {
      It("should be a novel", func() {
      Expect(longBook.CategoryByLength()).To(Equal("NOVEL"))
      })
      })

      Context("With fewer than 300 pages", func() {
      It("should be a short story", func() {
      Expect(shortBook.CategoryByLength()).To(Equal("SHORT STORY"))
      })
      })
      })
      })


      Similarity there are other lifecycle methods like afterEach, justBeforeEach etc.






      share|improve this answer























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        Go does not have the inbuilt functionality to support tear up and down methods. However, there are multiple third-party packages that enable this. Out of all of these, I like the ginkgo package the most. It is very expressive and avoids code duplication.



        A sample test would look like



        var _ = Describe("Book", func() {
        var (
        longBook Book
        shortBook Book
        )

        BeforeEach(func() {
        longBook = Book{
        Title: "Les Miserables",
        Author: "Victor Hugo",
        Pages: 1488,
        }

        shortBook = Book{
        Title: "Fox In Socks",
        Author: "Dr. Seuss",
        Pages: 24,
        }
        })

        Describe("Categorizing book length", func() {
        Context("With more than 300 pages", func() {
        It("should be a novel", func() {
        Expect(longBook.CategoryByLength()).To(Equal("NOVEL"))
        })
        })

        Context("With fewer than 300 pages", func() {
        It("should be a short story", func() {
        Expect(shortBook.CategoryByLength()).To(Equal("SHORT STORY"))
        })
        })
        })
        })


        Similarity there are other lifecycle methods like afterEach, justBeforeEach etc.






        share|improve this answer












        Go does not have the inbuilt functionality to support tear up and down methods. However, there are multiple third-party packages that enable this. Out of all of these, I like the ginkgo package the most. It is very expressive and avoids code duplication.



        A sample test would look like



        var _ = Describe("Book", func() {
        var (
        longBook Book
        shortBook Book
        )

        BeforeEach(func() {
        longBook = Book{
        Title: "Les Miserables",
        Author: "Victor Hugo",
        Pages: 1488,
        }

        shortBook = Book{
        Title: "Fox In Socks",
        Author: "Dr. Seuss",
        Pages: 24,
        }
        })

        Describe("Categorizing book length", func() {
        Context("With more than 300 pages", func() {
        It("should be a novel", func() {
        Expect(longBook.CategoryByLength()).To(Equal("NOVEL"))
        })
        })

        Context("With fewer than 300 pages", func() {
        It("should be a short story", func() {
        Expect(shortBook.CategoryByLength()).To(Equal("SHORT STORY"))
        })
        })
        })
        })


        Similarity there are other lifecycle methods like afterEach, justBeforeEach etc.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        Mayank Patel

        3,62242644




        3,62242644






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53238373%2ftesting-lifecyle-in-go-is-it-possible-to-add-tear-up-and-down-method-without-du%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            Popular posts from this blog

            List item for chat from Array inside array React Native

            Thiostrepton

            Caerphilly