Fadelis / grpcmock

A gRPC Java testing tool to easily mock endpoints of gRPC services for IT or Unit testing
http://grpcmock.org
Apache License 2.0
144 stars 13 forks source link

Support JUnit 5 @Nested #21

Closed Noreaster76 closed 1 year ago

Noreaster76 commented 1 year ago

With a structure like this:

@ExtendWith(GrpcMockExtension.class)
class TestClass {

  private ManagedChannel channel;

  @BeforeEach
  void setupChannel() {
    channel = ManagedChannelBuilder.forAddress("localhost", GrpcMock.getGlobalPort())
        .usePlaintext()
        .build();
  }

  @AfterEach
  void shutdownChannel() {
    Optional.ofNullable(channel).ifPresent(ManagedChannel::shutdownNow);
  }

  @Nested
  @DisplayName("when the request succeeds")
  class RequestSucceedsTest {

    @BeforeEach
    void setUpSuccessfulGrpcRequest() {
      stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod())
    .willReturn(successResponse));
    }

    @Test
    @DisplayName("it returns foo")
    void returnsFoo() {
      // request and assertions here
    }
  }

  @Nested
  @DisplayName("when the request fails")
  class RequestFailsTest {

    @BeforeEach
    void setUpUnsuccessfulGrpcRequest() {
      stubFor(unaryMethod(SimpleServiceGrpc.getUnaryRpcMethod())
    .willReturn(failureResponse));
    }

    @Test
    @DisplayName("it returns bar")
    void returnsBar() {
      // request and assertions here
    }
  }
}

Expected

The stubbing works properly, and the tests pass.

Actual

One of the two tests encounters a StatusRuntimeException, with a message of Already terminated.

Fadelis commented 1 year ago

It seems that each nested class triggers afterAll callback of the extension, which shutdowns the server. That's a strange behaviour of these nested classes, but I guess I can add a check and skip shutdown if the callback is coming from a nested class and not from overall class. Edit: fixed in 0.8.0 version