✍️
Notes.md
  • Table of contents
  • React.Js
    • React Hooks
    • Old :- React : Using Classes
  • Blockchain
    • Solidity
    • Custom ERC20 token
    • Contract
  • Tools and Tech
    • Docker
    • Git version Control
  • Java
    • Data & Data Types
    • IO in Java
    • Data Structures
      • Array in Java
      • Collections in Java
      • Map in Java
      • Enums in Java
      • Linked List in Java
      • List in Java
      • Queues & Stacks
      • Set in Java
      • TreeSet and TreeMap
    • Object Oriented Programming
      • Object Class Methods and Constructor
      • Immutable Class & Objects
      • Constructors
      • Visibility
      • Generics
    • Threads in Java
    • Useful Stuff Java
      • Lambda & Stream
    • Keywords in Java
      • Annotations
      • Comparators
      • Packages in Java
    • Miscellaneous
    • Articles to refer to
  • Golang
    • Competitive Programming in Go
    • Testing simple web server
    • Learning Go : Part 1
    • Maps vs slices
    • Golang Garbage Collector 101
    • Things Golang do differently
    • Go Things
  • Linux
    • Shell programming
    • Linux Commands Part 1 - 4
    • Linux Commands Part 5 - 8
    • Linux Commands Part 9 - 10
  • Software Design
    • Solid Design
    • OOPS
    • Design Patterns
      • Creational Design Pattern
        • Builder DP
        • Factory DP
        • Singleton DP
      • Adapter DP
      • Bridge DP
      • Iterator DP
      • State DP
      • Strategy DP
      • Behavioral Design Pattern
        • Observer DP
      • Structural Design Pattern
        • Facade DP
  • Cloud
    • Google Cloud Platform
      • GCP Core Infrastructure
      • Cloud Networking
  • Spring Boot
    • Spring Basics
      • Spring Beans
      • Important Annotations
      • Important Spring Things
      • Maven Things
      • Spring A.O.P
    • Spring Boot Controller
      • Response Entity Exception Handling
    • Spring Things
    • Spring MVC
    • Spring Data
      • Redis
      • Spring Data JPA
      • JDBC
    • Apache Camel
  • Miscellaneous
    • Troubleshooting and Debugging
Powered by GitBook
On this page
  • Testing web server in Golang
  • Testing
  • To record the response from the writer
  • To verify
  • Full code server.go
  • Full code main_test.go

Was this helpful?

  1. Golang

Testing simple web server

Testing web server 101

Testing web server in Golang

  • create a file with name <anything>_test.go, these files are ignore by compiler

  • write a func matching func TestXxx(*testing.T) where Xxx does not start with a lowercase letter. The function name serves to identify the test routine.

  • To run the test : go test

Testing

  • inorder to test the handler, we call it by passing http.ResponseWriter and *http.Request

  • to create a new Request

req, err := http.NewRequest(
    http.MethodGet,                 // defining method of HTTP request
    "http://localhost:8080/",       // Url to hit
    nil,                            // Body (taking nil right now)
)

// checking for any errors            
if err != nil {
    t.Fatalf("Could not create a request %v", err)
}

To record the response from the writer

rec := httptest.NewRecorder()

To verify

// calling the function
helloWorldEndPoint(rec, req)

// checking status code
if rec.Code != http.StatusOK {
    t.Errorf("accepted status 200, got %v", rec.Code)
}

// checking the msg returned
if !strings.Contains(rec.Body.String(), "hello world") {
    t.Errorf("unexpected body in response %q", rec.Body.String())
}

Full code server.go

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {

    http.HandleFunc("/", helloWorldEndPoint)
    fmt.Println("Server :  http://localhost:8080")
    log.Fatal(http.ListenAndServe(":8080", nil))

}

func helloWorldEndPoint(writer http.ResponseWriter, request *http.Request) {

    fmt.Fprintf(writer, "hello world")

}

Full code main_test.go

package main

import (
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"
)

func TestHandler(t *testing.T) {

    req, err := http.NewRequest(
        http.MethodGet,
        "http://localhost:8080/",
        nil,
    )

    if err != nil {
        t.Fatalf("Could not create a request %v", err)
    }

    rec := httptest.NewRecorder()
    helloWorldEndPoint(rec, req)

    if rec.Code != http.StatusOK {
        t.Errorf("accepted status 200, got %v", rec.Code)
    }

    if !strings.Contains(rec.Body.String(), "hello world") {
        t.Errorf("unexpected body in response %q", rec.Body.String())
    }

}
PreviousCompetitive Programming in GoNextLearning Go : Part 1

Last updated 3 years ago

Was this helpful?