Iman Tumorang

Software Engineer

How I made a simplest and useful library in Golang by learning Reflection’s work

Learn by doing: a reflection in Golang

Random text , searched from google images

A few a months ago, I was creating a simple library in golang, to help golang engineers when testing their function. It just a simple library that will generate fake and random data based on their struct. The idea comes when I was creating unit testing in every function I have, and making different struct , it’s a wasting time.

The libary can seen here

How to use it :

$ go get github.com/bxcodec/faker

Then import into your test file.

This simple library I made with utilizing the reflection feature in golang. The work is simple , you only define you struct and my library will generate you a dummy data based on your struct.

Example :

When you run that your object will filled with random data :

$ go run main.go
$ {Int:37 String:LOftACEPfclEWQDBqAaaqyVis Bool:false SString:[yWgdk
ZQtbTmi] Struct:{Number:36 Height:0.021622694665801242
AnotherStruct:{Image:wUvHuSlyJYknWbqUbWtYGrMrZ}}}

Even you have a nested struct, as long as they do not pointer struct , they will safe to generated.

Good, How did you do that?

Reflection

In golang, there is a built in package that we can use for reflection data type it’s called reflect . You can see what reflect can do in the official documentations https://golang.org/pkg/reflect/

Basically , I just get the data type, then random data based on it’s type.

var a int64 

ref :=reflect.ValueOf(&a) //will return reflect.Value objects ;
//Pass with refferences for data
//manipulation

ref=reflect.Indirect(ref) //accessing the value only that pointed by
//ref

kind:= ref.Kind() // will return the kind of the reflected value

if kind == reflect.Int64{
  val:= int64(100)  //Data will assigned. For fake data, this 
//should randomized
  ref.Set(reflect.ValueOf(val)) //Set the value
}

fmt.Println("Value of a ", a) //Will print 100

Live example you could run here

Just as simple as it. Now I can generate a dummy data for my struct and help me when doing automation testing with random data.

But, this library still need more improvements, because it’s still can’t randomize data for array of struct. I’ve tried many ways, but still not good, maybe it’s impossible to do, or maybe I still need to learn more.

Happy coding…. :)

If you have a question , or need more explanation, or something, that I can not explain well here, you can ask me from my linkedin or email me. Thank you

More by Iman Tumorang

Topics of interest

More Related Stories