V
V
Vsevolod Kaloshin2017-01-19 09:28:56
go
Vsevolod Kaloshin, 2017-01-19 09:28:56

How to lock a struct method that is called in another method of the same struct in Golang?

Hello!
When writing tests, I ran into one problem. There is testable code;

Do() error
}
type MyInterface interface {
   MethodA() error
   MethodB() error
}
type MyStruct struct {
  OtherStruct OtherInterface
}
func(s *MyStruct) MethodA() error {
  return s.MethodB()
}
func(s *MyStruct) MethodB() error {
  return s.OtherStruct.Do()
}

And the code that tests MethodB
ype MockOtherStruct struct {
  Do_Error error
}
func (t *MockOtherStruct) Do() error {return t.Do_Error}


TestMyStruct_MethodB(t *testing.B) {
  expectedError = nil
  mos := &MockOtherStruct{
    Do_Error: nil
  }
  ms := MyStruct{
   OtherStruct: mos,
  }
  err := ms.MethodB()
  if err != expectedError {
    t.Fatal(err)
  }      
}

How do I test MethodA by locking into MethodB?
This example is simple, because in real code, a structure can have many structure variables that implement different interfaces. Also, the logic of the various methods can be quite complex to make it easy to use shackled variables.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeniy Ivakha, 2017-01-19
@ivahaev

No need to wet, you need to simplify the logic.
Also, *testing.B is used for benchmarks. You need to use *testing.T for testing.

N
Nikita, 2017-01-19
@jetu

Look towards testify

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question