Skip to content

Commit

Permalink
Merge pull request #78 from JosiahWitt/interface-t
Browse files Browse the repository at this point in the history
Add `InterfaceT` method for exposing the scoped `ensuring.T`
  • Loading branch information
JosiahWitt authored Mar 3, 2023
2 parents 17a75fc + 15ac1fe commit 2ec9e16
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
10 changes: 10 additions & 0 deletions ensuring/ensuring.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,16 @@ func (e E) T() *testing.T {
return t
}

// InterfaceT exposes the scoped [T]. Usually, [E.T] will be
// more useful, as it exposes the full [testing.T]. InterfaceT
// is intended for use when a non-[testing.T] type was provided
// to `ensure.New`, as in the case of mocking.
func (e E) InterfaceT() T {
c := e(nil)
c.markRun()
return c.t
}

// GoMockController exposes a GoMock Controller scoped to the current test context.
// Learn more about GoMock here: https://github.com/golang/mock
func (e E) GoMockController() *gomock.Controller {
Expand Down
46 changes: 46 additions & 0 deletions ensuring/ensuring_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,52 @@ func TestET(t *testing.T) {
})
}

func TestEInterfaceT(t *testing.T) {
type MockT struct {
ensuring.T
Unique string
}

t.Run("passes through T when not using ensure.Run", func(t *testing.T) {
mockT := setupMockTWithCleanupCheck(t)
wrappedMockT := MockT{T: mockT, Unique: "hello"}
testhelper.SetTestContext(t, wrappedMockT, testctx.New(wrappedMockT, wrapEnsure))
ensure := ensure.New(wrappedMockT)

if ensure.InterfaceT().(MockT).Unique != "hello" {
t.Fatal("didn't return the expected T")
}
})

t.Run("returns nested T when using ensure.Run", func(t *testing.T) {
ctrl := gomock.NewController(t)

innerMockT := setupMockTWithCleanupCheck(t)
innerMockT.EXPECT().Helper().AnyTimes()
wrappedInnerMockT := MockT{T: innerMockT, Unique: "hello"}

innerMockTestCtx := mock_testctx.NewMockContext(ctrl)
innerMockTestCtx.EXPECT().T().Return(wrappedInnerMockT).AnyTimes()
testhelper.SetTestContext(t, wrappedInnerMockT, innerMockTestCtx)

outerMockT := setupMockTWithCleanupCheck(t)
outerMockT.EXPECT().Helper().AnyTimes()

outerMockTestCtx := mock_testctx.NewMockContext(ctrl)
testhelper.SetTestContext(t, outerMockT, outerMockTestCtx)
outerMockTestCtx.EXPECT().Run("inner", gomock.Any()).Do(func(_ string, fn func(testctx.Context)) {
fn(innerMockTestCtx)
})

ensure := ensure.New(outerMockT)
ensure.Run("inner", func(ensure ensuring.E) {
if ensure.InterfaceT().(MockT).Unique != "hello" {
t.Fatal("didn't return the expected T")
}
})
})
}

func TestEGoMockController(t *testing.T) {
mockT := setupMockTWithCleanupCheck(t)
mockT.EXPECT().Cleanup(gomock.Any()).AnyTimes() // Setup by GoMock Controller
Expand Down

0 comments on commit 2ec9e16

Please sign in to comment.