Skip to content

How to unit test? #903

Answered by abhinav
tigerinus asked this question in Q&A
Jul 27, 2022 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

To unit test just ServiceB, you can write a unit test that calls NewServiceB directly—like a regular function.

func TestServiceB(t *testing.T) {
  mockServiceA := // ...
  NewServiceB(mockServiceA)
  // ...
}

However, to test ServiceB integration with Fx, you can use fxtest.
For this, you need to either duplicate the list of arguments to fx.New, or extract them into a helper function.
Internally, most of our applications have a helper opts() fx.Option function that looks like this:

func opts() fx.Option {
  return fx.Options(
    fx.Provide(service.NewServiceA),
    fx.Provide(service.NewServiceB),
    fx.Invoke(runHTTPListener),
  )
}

func main() {
  app := fx.New(opts()...)
  // ...
}

W…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@tigerinus
Comment options

@abhinav
Comment options

abhinav Jul 27, 2022
Collaborator

Answer selected by tigerinus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants