Golang Testing Basics Quick Tutorial

แชร์
ฝัง
  • เผยแพร่เมื่อ 2 ธ.ค. 2024
  • This video tutorial covers Golang testing basics.
    The code:
    // math.go
    package math
    import "errors"
    // Add adds two integers and returns the result.
    func Add(a, b int) int {
    return a + b
    }
    // Divide divides two numbers and returns an error if the divisor is zero.
    func Divide(a, b float64) (float64, error) {
    if b == 0 {
    return 0, errors.New("division by zero")
    }
    return a / b, nil
    }
    // math_test.go
    package math
    import (
    "testing"
    "github.com/stretchr/testify/assert"
    )
    // go test ./...
    // simple test using assert
    func TestAdd(t *testing.T) {
    result := Add(2, 3)
    expected := 5
    assert.Equal(t, expected, result, "Add(2, 3) should equal 5")
    }
    // Table-Driven Tests
    func TestAddMultipleCases(t *testing.T) {
    testCases := []struct {
    name string
    a, b int
    expected int
    }{
    {"Positive numbers", 2, 3, 5},
    {"Zero", 0, 0, 0},
    {"Negative numbers", -1, -1, -2},
    {"Mixed signs", -2, 3, 1},
    }
    for _, tc := range testCases {
    tc := tc // Capture range variable
    t.Run(tc.name, func(t *testing.T) {
    result := Add(tc.a, tc.b)
    assert.Equal(t, tc.expected, result)
    })
    }
    }
    // Testing Error Conditions
    func TestDivide(t *testing.T) {
    testCases := []struct {
    name string
    a, b float64
    expected float64
    expectError bool
    }{
    {"Valid division", 10, 2, 5, false},
    {"Division by zero", 10, 0, 0, true},
    }
    for _, tc := range testCases {
    tc := tc // Capture range variable
    t.Run(tc.name, func(t *testing.T) {
    result, err := Divide(tc.a, tc.b)
    if tc.expectError {
    assert.Error(t, err)
    } else {
    assert.NoError(t, err)
    assert.Equal(t, tc.expected, result)
    }
    })
    }
    }
    // Code Coverage Analysis: Assess how much of your code is tested.
    // go test -coverprofile=coverage.out
    // go tool cover -html=coverage.out -o coverage.html
    If you want in-depth tutorial on Docker & Kubernetes along with gRPC, fully explained from end-to-end, then check out this course on Microservices: www.justforlea...
    This is not free but if you are a student or can't afford it then feel free to email to justforlearnings@gmail.com explaining why and I will be able to give it for free. But in condition that you will be finishing the course completely within a month. :)

ความคิดเห็น • 1

  • @mafia2117
    @mafia2117 6 วันที่ผ่านมา

    Bhai thanks for the video, looking forward to more and more videos