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 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata