jeudi 29 novembre 2018

Testing Basic Slice / Array

So am new to the whole unit testing landscape. I am using Go 1.11.2 and I have built the below func, its for a wider example project I am hoping to be able to build. But I thought that as some of these functions will be simple, it would be a good place to start some testing.

Function below builds/makes a slice - as I see it this is an array, has I have given it a hard length. Then once built it returns the data, but I am unsure how best to go - :) - about doing the testing for this function?

func makeNumbers() []int {
  numbs := make([]int, 10)

  numbs[0] = 0
  numbs[1] = 1
  numbs[2] = 2
  numbs[3] = 3
  numbs[4] = 4
  numbs[5] = 5
  numbs[6] = 6
  numbs[7] = 7
  numbs[8] = 8
  numbs[9] = 9

  return numbs
}

This is what I have done so far:

func TestMakeNumbers(t *testing.T) {

  t.Run("collection of 5 numbers", func(t *testing.T) {

    got := makeNumbers()
    want := make([]int, 6)

    if reflect.DeepEqual(got, want) {
        t.Errorf("got %d want %d given", got, want)
    }
  })

  t.Run("collection of any size", func(t *testing.T) {
    // numbers := []int{1, 2, 3}

    got := makeNumbers()
    want := make([]int, 10)

    if reflect.DeepEqual(got, want) {
        t.Errorf("got %d want %d given", got, want)
    }
  })

}

The testing function is in main_test.go while the makeNumbers function is in my main.go file.

When I run go test this passes, but I am not sure I am doing it right?

What I wanted, is to build two conditions, one where it would fail, e.g. makeNumbers set to return a bigger array or an array of strings... something like that. Then the next condition would be to make a condition telling it what I need, e.g. an array of int's 0-10.

All help most welcome.

Thanks.

Aucun commentaire:

Enregistrer un commentaire