首页 > 解决方案 > 我如何应用单元测试来检查 golang 的闰年?

问题描述

我想做单元测试并检查日期是否是闰年,在这种情况下我如何应用单元测试,我不知道在这种情况下该怎么做?

我已经创建了我的函数并且工作正常,我还有一个 JSON 文件,其中包含人员列表及其生日日期!

希望能提供一些有关如何解决此问题的反馈或建议!谢谢

BD.go:

 package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "time"
)

// Users struct which contains
// an array of users
type Users struct {
    Users []User `json:"users"`
}

// User struct which contains a name
// a type and a list of social links
type User struct {
    Firstname  string `json:"fname"`
    Secondname string `json:"lname"`
    Date       string `json:"date"`
}

var users Users
var user User

func Birthday() {
    // Open our jsonFile
    jsonFile, err := os.Open("users.json")
    // if we os.Open returns an error then handle it
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("Successfully Opened users.json")
    // defer the closing of our jsonFile so that we can parse it later on
    defer jsonFile.Close()

    // read our opened xmlFile as a byte array.
    byteValue, _ := ioutil.ReadAll(jsonFile)

    // we initialize our Users array
    // we unmarshal our byteArray which contains our
    // jsonFile's content into 'users' which we defined above
    json.Unmarshal(byteValue, &users)
    IsLeapYear("users.json")
}

func IsLeapYear(user string) bool {
    // we iterate through every user within our users array and
    // print out the user Type, their name
    for i := 0; i < len(users.Users); i++ {
        date, err := time.Parse("2006/01/02", users.Users[i].Date)
        if err != nil {
            date, err = time.Parse("2006-01-02", users.Users[i].Date)
            // date, err = time.Parse("2006 01 02", users.Users[i].Date)
            if err != nil {
                log.Fatal("unsupported date format:", err)
            }
        }

        // check if the date is a leap year, ex: 29 is not a leap year but 28th is !

        if date.Day()%400 == 0 || (date.Day()%4 == 0 && date.Day()%100 != 0) {
            fmt.Println("User First Name: " + users.Users[i].Firstname)
            fmt.Println("User Second Name: " + users.Users[i].Secondname)
            fmt.Println("User Date: " + users.Users[i].Date)
            fmt.Println(users.Users[i].Date, "is a Leap Year ✨ ✨ ✨&quot;)

            // checking if the date.day matches today's date
            if date.Day() == time.Now().Day() {
                fmt.Println("User First Name: " + users.Users[i].Firstname)
                fmt.Println("User Date: " + users.Users[i].Date)
                fmt.Println("TODAY IS YOUR BIRTHDAY, Happy birthday !!!    ")

                // not ur birthday today because the date in the json doesn't match todays date
            } else {

                fmt.Println("TODAY IS NOT YOUR BIRTHDAY..!!!")

            }

        } else {
            fmt.Println("User First Name: " + users.Users[i].Firstname)
            fmt.Println("User Second Name: " + users.Users[i].Secondname)
            fmt.Println("User Date: " + users.Users[i].Date)
            fmt.Println(users.Users[i].Date, " is Not a Leap Year    ")
        }

    }

    return false
}

func main() {
    Birthday()

}

bd_test.go:

包主

import (
    "testing"
    "time"

    "github.com/stretchr/testify/assert"
)

//main_test.go
type dateTest struct {
    date   time.Time
    expect bool
}

var dateTests = []dateTest{
    {"2021-07-28", true},
    {time.Date(2021,9,10), false},
}

func TestIsLeapYear(t *testing.T) {
    for _, tc := range dateTests {
        result := IsLeapYear(tc.date)
        assert.Equal(t, tc.expect, result)
    }
}

用户.JSON:

{
    "users": [
      {
        "Fname": "Johnny",
        "Lname":"mane",
        "date":"1982/01/08"
      },
      {
        "Fname": "Wayne",
        "Lname":"Bruce",
        "date":"1965/01/30"
      },
      {
        "Fname": "Gaga",
        "Lname":"Lady",
        "date":"1986/03/08"
      },
      {
        "Fname": "radio",
        "Lname":"head",
        "date":"1988/02/29"
      },
      {
        "Fname": "Mario",
        "Lname":"torres",
        "date":"1996/09/04"
      },
      
      {
        "Fname": "robert",
        "Lname":"Alex",
        "date":"1991/12/05"
      },
      {
        "Fname": "Julia",
        "Lname":"sevak",
        "date":"1991-03-28"

      },
      {
        "Fname": "feb",
        "Lname":"robert",
        "date":"1995-05-24"

      },
      {
        "Fname": "Liam",
        "Lname":"Noah",
        "date":"2002-10-04"

      },
      {
        "Fname": "alex",
        "Lname":"sam",
        "date":"2021/10/21"

      }
      
      }

    ]
  }

标签: unit-testinggotesting

解决方案


您的代码需要进行一些重构以使其可测试。目前您无法真正测试代码,因为代码中的函数不返回任何内容。在单元测试中,您调用一个函数并验证它的输出(一般来说)。

因此,为了使您的代码可测试,您必须在单独的函数中重构代码的某些部分。我将向您展示闰年的示例:

//main.go
func IsLeapYear(date time.Time) bool {
  if date.Year() % 400 == 0 {
    return true
  }
  return date.Year()%4 == 0 && date.Year()%100 != 0
}

在您的测试文件中:

//main_test.go
type dateTest struct {
  date time.Time
  expect bool
}

var dateTests = []dateTest{
  // your test data
}

func TestIsLeapYear(t *testing.T){
  for _, tc := range dateTests {
    result := IsLeapYear(tc.data)
    assert.Equal(t, tc.expect, result)
  }
}


推荐阅读