diff --git a/CHANGELOG.md b/CHANGELOG.md index b30c21c45..a571d75ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## Unrelease -- No changes yet. +## Unreleased +### Added +- fxtest: Add WithTestLogger option that uses a `testing.TB` as the + Fx event logger. ## [1.20.1](https://github.com/uber-go/fx/compare/v1.20.0...v1.20.1) - 2023-10-17 diff --git a/app_test.go b/app_test.go index c9b9000b0..cc8fc426a 100644 --- a/app_test.go +++ b/app_test.go @@ -53,7 +53,7 @@ func NewForTest(tb testing.TB, opts ...Option) *App { // Provide both: Logger and WithLogger so that if the test // WithLogger fails, we don't pollute stderr. Logger(fxtest.NewTestPrinter(tb)), - WithLogger(func() fxevent.Logger { return fxtest.NewTestLogger(tb) }), + fxtest.WithTestLogger(tb), } opts = append(testOpts, opts...) @@ -73,7 +73,7 @@ func validateTestApp(tb testing.TB, opts ...Option) error { // Provide both: Logger and WithLogger so that if the test // WithLogger fails, we don't pollute stderr. Logger(fxtest.NewTestPrinter(tb)), - WithLogger(func() fxevent.Logger { return fxtest.NewTestLogger(tb) }), + fxtest.WithTestLogger(tb), } opts = append(testOpts, opts...) diff --git a/fxtest/app.go b/fxtest/app.go index 9ce2e8b1f..427f95422 100644 --- a/fxtest/app.go +++ b/fxtest/app.go @@ -24,7 +24,6 @@ import ( "context" "go.uber.org/fx" - "go.uber.org/fx/fxevent" ) // App is a wrapper around fx.App that provides some testing helpers. By @@ -38,7 +37,7 @@ type App struct { // New creates a new test application. func New(tb TB, opts ...fx.Option) *App { allOpts := make([]fx.Option, 0, len(opts)+1) - allOpts = append(allOpts, fx.WithLogger(func() fxevent.Logger { return NewTestLogger(tb) })) + allOpts = append(allOpts, WithTestLogger(tb)) allOpts = append(allOpts, opts...) app := fx.New(allOpts...) diff --git a/fxtest/printer.go b/fxtest/printer.go index 73f0f8f74..c16c155b6 100644 --- a/fxtest/printer.go +++ b/fxtest/printer.go @@ -32,6 +32,14 @@ func NewTestLogger(t TB) fxevent.Logger { return fxlog.DefaultLogger(testutil.WriteSyncer{T: t}) } +// WithTestLogger returns an fx.Option that uses the provided TB +// as the destination for Fx's log output. +func WithTestLogger(t TB) fx.Option { + return fx.WithLogger(func() fxevent.Logger { + return NewTestLogger(t) + }) +} + type testPrinter struct { TB }