-1

I am looking to mock some methods for unit testing. Unfortunately, the code is not structured really well.

var config = struct { abc *abc }

func Init(arg1) {
    // config.abc = newAbc(arg2, arg3)
}   

func UnitTestThis() { 
    //some code here 

    config.abc.Search(arg4,arg5) 

    //code here 
}

How do I unit test the UnitTestThis function, mocking the results of Search method? I have been trying to create an interface and mock the methods, but been unable to do so.

mkopriva
  • 35,176
  • 4
  • 57
  • 71
Gyanendra Singh
  • 895
  • 2
  • 13
  • 30

1 Answers1

1

If the config.abc field is a concrete type (or a pointer to a concrete type), you can't really mock it.

You need some refactoring.

With interface

Best would be to change the type of config.abc to interface type, so in tests you can create your own implementation and assign to it, and you can do whatever you want to in it.

Using a method value on config.abc.Search

Another option is to create a variable of function type to hold the method value of config.abc.Search(), and in tests assign a new value to it, a function literal for example.

This is how it could look like:

var config = struct{ abc *abc }{}

var searchFunc func(arg4Type, arg5Type)

func Init(arg1) {
    config.abc = newAbc(arg2,arg3)
    searchFunc = config.abc.Search
}

func UnitTestThis() {
    //some code here
    searchFunc(arg4, arg5)
    //code here
}

Read more about this here: Is it possible to mock a function imported from a package in golang?

icza
  • 389,944
  • 63
  • 907
  • 827
  • Can searchFunc be a reciever? If so, what would this syntax look like? – Gyanendra Singh Nov 16 '17 at 13:27
  • @GyanendraSingh I don't understand the question. – icza Nov 16 '17 at 13:31
  • var searchFunc func(arg2Type, arg3Type) -> how would it look like for a reciever, along with definition? – Gyanendra Singh Nov 16 '17 at 13:32
  • @GyanendraSingh I still don't understand. `searchFunc` is a variable of function type, and `Init()` initializes it with a method value which implicitly stores the receiver value. – icza Nov 16 '17 at 13:34
  • Thanks icza! I was able to set up the tests using function variable. However, this is problematic in the sense that it makes it open to abuse/bugs, if assigned to some other function matching the definition. I will try to set up the same using interfaces. – Gyanendra Singh Nov 17 '17 at 11:53
  • Also, config.abc is a struct. – Gyanendra Singh Nov 17 '17 at 12:56