gstest

package
v1.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 10, 2025 License: Apache-2.0 Imports: 3 Imported by: 0

Documentation

Overview

Package gstest provides unit testing utilities for dependency injection in Go-Spring framework.

Key Features:

  • Test environment configuration: jobs and servers are disabled, and the "test" profile is automatically activated
  • Autowire failure tolerance: non-critical autowiring errors are tolerated so that missing beans do not break tests
  • Type-safe mocking: compile-time checked MockFor/With methods for registering mock beans
  • Context lifecycle management: TestMain starts and stops the Go-Spring context automatically
  • Injection helpers: Get[T](t) and Wire(t, obj) simplify bean retrieval and dependency injection

Usage Pattern:

// Step 1: Register your mock beans before tests run
// by calling `MockFor[T]().With(obj)` inside an `init()` function.
func init() {
    gstest.MockFor[*Dao]().With(&MockDao{})
}

// Step 2: Implement TestMain and invoke `gstest.TestMain(m, opts...)`
// to bootstrap the application context, execute all tests, and then shut it down.
// You can supply `BeforeRun` and `AfterRun` hooks to run code immediately before or after your test suite.
func TestMain(m *testing.M) {
	gstest.TestMain(m)
}

// Step 3: Write your test cases and use Get[T](t) or Wire(t, obj) to retrieve beans and inject dependencies.
func TestService(t *testing.T) {
    // Retrieve autowired test target
    service := gstest.Get[*Service](t)

    // Verify business logic
    result := service.Process()
    assert.Equal(t, expect, result)
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

func Get[T any](t *testing.T) T

Get gets the bean from the app context.

func TestMain

func TestMain(m *testing.M, opts ...RunOption)

TestMain executes test cases and ensures shutdown of the app context.

func Wire

func Wire[T any](t *testing.T, obj T) T

Wire injects dependencies into the object.

Types

type BeanMock

type BeanMock[T any] struct {
	// contains filtered or unexported fields
}

BeanMock is a mock for bean.

func MockFor

func MockFor[T any](name ...string) BeanMock[T]

MockFor creates a mock for bean.

func (BeanMock[T]) With

func (m BeanMock[T]) With(obj T)

With registers a mock bean.

type RunOption

type RunOption func(arg *runArg)

func AfterRun

func AfterRun(fn func()) RunOption

AfterRun specifies a function to be executed after all testcases.

func BeforeRun

func BeforeRun(fn func()) RunOption

BeforeRun specifies a function to be executed before all testcases.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL