Monday, July 8, 2019

GoLang: Initialization before the execution of init()

Problem Definition

I have this goLang package which reads a JSON config file and sets up a map. I didn't want to call a separate method to load the file and set up the map. I wanted this to happen in the beginning automatically.
So I created init() method which loads the file and initializes the map with required configuration.

Problem

I fell into problem when I wrote unit test.

For the test I wanted to load with mocked content, not the actual file content. I actually didn't want to load the file at all.

So I created a variable fileReader as an instance of ioutil.ReadFile() method. It allows me to inject mocked file reader as dependency and execute whatever I want.

But as I said earlier, I had implemented init() method to read the file. This init() executed in the beginning before I was able to inject my mocked file reader.

Solution

Clearly the solution was to find a way to inject the dependency before the init() method executes. Fortunately I found a way to do that. Its using the following:
        // executes becore init() method so that fileReader can be injected
        var _ = func() (_ struct{}) {
          fileReader = mockedFileReader
          return
        }()
      

Code Illustration

Packakge Implementation

Test Implementation








1 comment:

  1. As stated by Stanford Medical, It is really the one and ONLY reason women in this country get to live 10 years longer and weigh 19 kilos lighter than us.

    (And really, it is not about genetics or some secret exercise and absolutely EVERYTHING to related to "how" they are eating.)

    P.S, What I said is "HOW", and not "WHAT"...

    Tap this link to uncover if this quick quiz can help you discover your real weight loss possibilities

    ReplyDelete