0

I want to mock my Cosmos database call which returns a ResourceResponse, however there is no public constructor to do so. I've seen that it's been updated in C# to provide public constructor for testing, but I haven't seen anything related to Java. Is this possible to instantiate this object for testing in Java yet?

Artanis
  • 561
  • 1
  • 7
  • 26
  • Have you referred to https://github.com/Azure/azure-cosmosdb-java/issues/138? – Jim Xu Jun 30 '20 at 07:11
  • @JimXu that is regarding ResourceResponse being a final class, but it doesn't address there being no public constructor. So I can't create a sample ResourceResponse to return from the mocked call. – Artanis Jun 30 '20 at 15:14
  • I believe you can mock constructors as well using mockit: https://stackoverflow.com/questions/39701670/mocking-a-private-constructor – Kushagra Thapar Jul 13 '20 at 16:59

1 Answers1

0

Why don't you have your business logic in a service object which depends on a repository object for cosmos access? You can then mock out the repository and test the business logic in the service object. The repository will not have any business logic so you don't have to unitest it. Offcource, the repository will be tested as apart of the integration test.

Check out the following Test call: https://github.com/RaviTella/store/blob/master/src/test/java/com/ratella/store/model/cart/DefaultCartServiceUnitTest.java

I have a CartService which depends on CartRepository. I mock out the CartRepository with Mockito.

@BeforeEach
    void initAll() {
        cartRepositoryMock = mock(CartRepository.class);
    }

@Test
public void addItemToANewCartTest(){
    Cart cart1 = new Cart();

    CartItem item1 = new CartItem();
    item1.setBookId("i1");
    item1.setPrice(new BigDecimal(40));
    when(cartRepositoryMock.getCartById("c1")).thenReturn(Mono.just(cart1));
    when(cartRepositoryMock.saveCart(cart1)).thenReturn(Mono.just(200));
    CartService cartService = new DefaultCartService(cartRepositoryMock);
    cartService.addItemToCart("c1",item1).subscribe();

    assertThat(cart1.getSubTotal()).isEqualTo(new BigDecimal(40));
    assertThat(cart1.getItems().size()).isEqualTo(1);
    verify(cartRepositoryMock,times(1)).saveCart(cart1);
    verify(cartRepositoryMock,times(0)).upsertCart(cart1);
}
RCT
  • 1,044
  • 1
  • 5
  • 12