drl37530 2018-07-19 03:35
浏览 70
已采纳

如何使用Golang实施单元测试程序?

I saw many blogs where they write how to do unit testing but I will understand theory portion and not understand how to implement the test case can anyone will tell me that how will I implement the first test case for more understanding with the unit testing. Here I'm implementing the small program for average:-

Folder structure is:-

main.go
average(Folder)----> math_test.go

code in the both file is:-

main.go

 package main

 import "fmt"
 import "testcases/average"

 func main() {
    xs := []float64{1,2,3,4}
    avg := m.Average(xs)
    fmt.Println(avg) 
 }

math_test.go

package math

import "testing"

func TestAverage(t *testing.T) {
  var v float64
  v = Average([]float64{1,2})
  if v != 1.5 {
    t.Error("Expected 1.5, got ", v)
  }
 }

ERROR:- go build testcases/average: no non-test Go files in /home/iron/go/src/testcases/average

Helping me I'm very thankful to you.

  • 写回答

2条回答 默认 最新

  • doulu2576 2018-07-19 04:39
    关注

    You have to change the package name with the main or math as @mkopriva and @whitespace said and place them into the same folder see in example

    main.go

    package main
    
    
    func Sum(x int, y int) int {
      return x + y
    }
    
    func main() {
      Sum(5, 5)
    }
    

    math_test.go

    package main
    
    import "testing"
    
    func TestSum(t *testing.T) {
       total := Sum(5, 5)
       if total != 10 {
          t.Errorf("Sum was incorrect, got: %d, want: %d.", total, 10)
       }
    }
    

    Output:-

    PASS ok testcases 0.001s

    And also a basic example of the testing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?