Posts

Showing posts from 2020

Go: Mockc로 인터페이스 모킹하기

Introduction 이미 Go 생태계에는 꽤 많은 모킹 라이브러리가 있습니다. 하지만 그중 대부분이 쉽게 배우고 사용하기 힘듭니다. 저는 그 이유가 테스트 코드에서 라이브러리에서 제공하는 특정 함수의 사용을 강제하기 때문이라 생각합니다. 이러한 함수들은 강력한 기능을 갖고있을 지라도, 보통은 비직관적이고 타입 세이프하지 않은 인터페이스를 제공하는 경우가 많습니다. 그래서 직관적이고 아주 간단한 방법으로 모킹하고 테스트 할 수 있도록 도와주는, ' Mockc ' 라는 라이브러리를 만들게 되었습니다. 그럼 살펴보도록 하겠습니다! Overview Mockc 는 목을 생성하기 위한 두 가지 방법을 제공합니다. 이 글에서는 Mock Generator 를 사용한 방법을 살펴보도록 하겠습니다. 일단, 커맨드라인 툴인 mockc 를 먼저 설치해보겠습니다. go get github.com/KimMachineGun/mockc/cmd/mockc 위 커맨드를 실행하셨다면, $GOPATH/bin 하위에 mockc 가 설치됐을 것입니다. 아래는 이 글에서 Mockc 를 통해 모킹할 인터페이스와 그의 간단한 구현체입니다. // cache.go package main type Cache interface { Get(key string) (val interface{}, err error) Set(key string, val interface{}) (err error) Del(key string) (err error) } type MapCache struct { m map[string]interface{} } func (c MapCache) Get(key string) (interface{}, error) { if c.m != nil { c.m = map[string]interface{}{} } return c.m[key], nil } func (c MapCache) Set(key string, val interface{}) er

Go: Interface Mocking With Mockc

Introduction There are so many mocking libraries in Go ecosystem. But most of them are very difficult to use and learn. I think the main reason is they force you to use specific functions for assertion. Even if those functions provide powerful features, they are usually not intuitive and type-safe. So, I created a simple mock generator so that you could test your code in an intuitive way. And its name is ' Mockc ' . Let's take an overview! Overview It provides two ways for generating mock. In this post, I'll only cover the way using Mock Generator . Before we get started, install the command-line tool mockc first! go get github.com/KimMachineGun/mockc/cmd/mockc Then you'll get mockc installed in your $GOPATH/bin . This is our target interface and simple implementation of it. // cache.go package main type Cache interface { Get(key string) (val interface{}, err error) Set(key string, val interface{}) (err error) Del(key string) (err error) } type MapC