2

I am stuck on how to write tests. I have following public function. GetAccountNumber() has its own logic. I would like to return a mock value for GetAccountNumber(). In Java, I could do when(object.method()).thenReturn("returnValue"). Is something similar available for go how can I accomplish that. I am going through bunch of go documentation but have not found anything useful yet.

func GetConfigName() string {
    var configName string
    accountNumber := GetAccountNumber()
    switch *accountNumber {
    case "123":
        configName = "test1"
    case "456":
        configName = "test2"

    return configName
}
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • Does [this](https://stackoverflow.com/a/62208922/3473875) help? – poWar Jun 12 '20 at 20:27
  • 1
    Generally speaking, mocks are not required--a simple stub is usually enough. But it's hard to say, since we can't see what `GetAccountNumber` does. – Jonathan Hall Jun 12 '20 at 20:32
  • @Flimzy I might be naive to ask this. Isn't the whole point of stubbing/mocking is that I don't need to know what GetAccountNumber does internally and just know that it returns a string. – Shailesh123 Jun 15 '20 at 14:47
  • No. The point of stubbing/mocking is not to be ignorant of what a function does--it is to limit what you test. If you don't stub out `GetAccountNumber`, then your test is _also_ testing `GetAccountNumber`, and a failure in your test won't tell you what's broken. – Jonathan Hall Jun 15 '20 at 16:30

1 Answers1

-2

For writing a unit test case for this function, we need to see the GetAccountNumber() function definition first.

Please see "Unit Testing made easy in Go" for more information on writing unit test cases in Go.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Alok Tripathi
  • 874
  • 10
  • 9
  • 3
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/26402641) – jizhihaoSAMA Jun 13 '20 at 14:44
  • There is perticular problem mentioned in the error, I think he need to learn about writing Unit test cases. I personally found that helpful when I was learning Golang. That's why I shared that. – Alok Tripathi Jun 14 '20 at 03:26
  • Thanks @AlokTripathi, you are correct I am learning go and also have to dig in the code base that my team has that does not have good coverage. I am trying to learn go along with writing unit tests. Isn't the whole point of stubbing/mocking is that we don't need to know what GetAccountNumber does internally and only know that it returns a string – Shailesh123 Jun 15 '20 at 14:45