Is there a way to mock a type assertion using gomock?

586 Views Asked by At

i'm new to golang and using Gomock for testing. I have generated the mock for the interface foo, but in my code theres a piece of logic that uses foo.(type).

May I know if theres a way to mock this and return a type of my choice? If not, what would be a good way to go about doing this? Thanks!

Eg. code snippet:

// assume structs A and B implements the interface `foo` 
type foo interface {...}
type A struct {...}
type B struct {...} 

func DoSomething(i foo) {
  // Is there a way to mock this type assertion for i here? 
  switch currentType := i.(type) {
  case *A: 
    ...
  case *B:
    ...
  default:
    ...
  }
}
1

There are 1 best solutions below

1
On

gomock generates new implementation for interface. (For interface Foo implementation is MockFoo struct). In your scenarion such mock will only cover default case.

Easiest way to deal with DoSomething(i foo) is to pass concrete implementations (testdata based on your scenario)