LoginSignup
2
2

More than 5 years have passed since last update.

Go的なのかどうかはわからないが時間だけは無い

Last updated at Posted at 2017-12-07

多分Go的なきれいな設計になってないからこういう具合に苦しむのだろうけど…
インタフェースに依存させよ的な実装、「なるほどこういうことか!」ってなるし、できればそうしたいんだけど、例えば前の記事みたいな例だとうぅーんって気分に陥る。

が、業務でやってるので、どうしても戦わねばならない敵がいる。

その名も

納期の魔女
特技:前に倒れる

である。

その上で、明日の平和のためにも自分の精神衛生のためにもテストコードは書いておきたい。

と、ここまで言い訳を並べた上で結局こうした。
2018/5/23 追記
同僚にもうちょっと補足してくれと言われたので足した

package main

type SugoiIF interface {
    Get() result
}

type result struct {
    mock string
}

type Sugoi struct {}

var NewSugoiApi = newSugoiApi

func newSugoiApi() SugoiIF {
    return &Sugoi{}
}

func (s *Sugoi) Get() result {
    return result{mock: "No"}
}

func main() {}

func ex() result {
    a := NewSugoiApi()
    b := a.Get()
    return b
}
package main

import (
    "testing"
    "fmt"
)

type mock struct {
    SugoiIF
}

func newSugoiApiDummy() SugoiIF {
    return &mock{}
}

func (m *mock) Get() result {
    return result{mock: "Yes"}
}

func TestEx(t *testing.T) {
    NewSugoiApi = newSugoiApiDummy
    a := ex()
    fmt.Println(a)
}

これでテストパッケからはsugoiapiのNewSugoiApiをSugoiIFを満たす(埋め込んでしまうのがラクチンだった)物体を返す関数で上書いてしまえばとりあえずやりたいことはできた。
このつきまとう「本当にこれで良いのか」感、BccDeveloperではじめてCのお勉強したときの気持ちとにている。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2