Another motivation I have heard used is that an os.Exit() from main by-passes defer(). So if you need to use defer from a "main-like" context move it to a function called from main(), do your defer(s) in it and then do the os.Exit() from main()..
On Friday 16 February 2024 at 01:23:57 UTC-8 Marcello H wrote: > My main acts just like a mini bootstrap to do as less as possible and hand > the real action over to start.Run() > But is is still testable. > > ``` > > var mainRunner = runner > > /* -------------------------- Methods/Functions ---------------------- */ > > // runner starts the application and can be overwritten in a test for > mocking. > func runner() error { > return start.Run() //nolint:wrapcheck // not needed here > } > > /* > main is the bootstrap of the application. > */ > func main() { > err := mainRunner() > if err != nil { > fmt.Println("Error:\n", libErrors.GetError(err)) > } > } > ``` > In an internal test, the mainRunner is mocked and can emulate an error if > needed. > func Test_Main_Error(t *testing.T) { > mainRunner = func() error { > return errors.New("test error") > } > > defer func() { > mainRunner = runner > }() > > captured := libCapture.Direct(func() { > main() > }) > > assert.Contains(t, captured, "test error") > } > > Op donderdag 15 februari 2024 om 10:05:11 UTC+1 schreef Brian Candler: > >> On Thursday 15 February 2024 at 00:08:44 UTC Jerry Londergaard wrote: >> >> If code is outside of the main function but still in the main package, it >> seems its testable like other functions? >> >> >> Yes indeed. >> >> >> I suspect though if one is putting tests in package main_test, then I >> guess you can't import the main package to test it :( >> >> >> Works fine as far as I can see: >> https://go.dev/play/p/7UtYP2j8hg6 >> >> (Tests don't run in the playground, unless you explicitly invoke a >> runner, but you can run this locally to demonstrate) >> > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/ee02c678-faa6-473c-bc81-5899ecf3b159n%40googlegroups.com.