L
L
lavagod2020-04-13 19:16:25
go
lavagod, 2020-04-13 19:16:25

Why do I get FAIL when testing in Golang?

Hello. Checking out the "testing" theme in Golang. I wrote a simple test (comparison of two numbers, 3 answer options), testing passes, test coverage is 100%, but why does the system write FAIL at the end? It seems that according to the documentation there should be PASS.

simple.go program

package main

func Question(a int, b int) int{

  if a > b {
    return 1
  } else if a < b {
    return 2
  } else {
    return 3
  }
}


simple_test.go program
package main

import (
  "testing"
)

type twoValue struct {
    x int
    y int
}

var tests = []twoValue{
    { 1,2 },
    { 2,1 },
    { 2,2 },
}

func TestQuestion(t *testing.T) {

  for _, value := range tests {
    res := Question(value.x, value.y)
    if res == 1 {
      t.Errorf("Больше")
    }
    if res == 2 {
      t.Errorf("Меньше")
    }
    if res == 1 {
      t.Errorf("Равно")
    }
  }
}


Reaction to `go test -v -cover` command
=== RUN   TestQuestion
--- FAIL: TestQuestion (0.00s)
    simple_test.go:26: Меньше
    simple_test.go:23: Больше
    simple_test.go:29: Равно
FAIL
coverage: 100.0% of statements
exit status 1
FAIL


I feel like I'm doing something wrong, but I can't figure out what exactly. Who will tell you what to fix? (By the way, you can probably write the data feed into the test in a simpler way, but in the lesson it was in this format, through the structure.)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2020-04-13
@lavagod

You call t.Errorf three times, resulting in FAIL for the test to be PASS - there shouldn't be a call to t.Errorf. Those. call t.Errorf only if an error occurs.
Should be something like this

type twoValue struct {
    x int
    y int
    expected int
}

var tests = []twoValue{
    { 1,2, 1 },
    { 2,1, 2 },
    { 2,2, 0 },
}

func TestQuestion(t *testing.T) {

  for _, value := range tests {
    res := Question(value.x, value.y)
    if res != value.expected {
      t.Errorf("при сравнении %v с %v получили, %v, а должно быть %v", value.x, value.y, res, value.expected)
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question