Skip to content

Instantly share code, notes, and snippets.

@atesibrahim
Last active June 30, 2022 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atesibrahim/7ce61df1036427df59d41d78142c0afc to your computer and use it in GitHub Desktop.
Save atesibrahim/7ce61df1036427df59d41d78142c0afc to your computer and use it in GitHub Desktop.
@ExtendWith(SpringExtension.class)
class ProductServiceImplTest {
@InjectMocks
private ProductServiceImpl productService;
@Mock
private ProductRepository productRepository;
@Mock
private CoinAmount coinAmount;
@Test
public void it_should_return_dispense_product_and_thank_you() {
//Given
Integer id = 1;
Product product = Product.builder().id(1).name("name").price(5.0).stock(10).build();
ProductRequest productRequest = ProductRequest.builder().id(1).build();
//when
when(coinAmount.getBalance()).thenReturn(10.0);
when(productRepository.findById(id)).thenReturn(Optional.ofNullable(product));
ProductDispenseResponse result = productService.dispense(productRequest);
//Then
verify(productRepository).findById(id);
assertThat(result.getProductName()).isEqualTo("name");
assertThat(result.getResponseMessage()).isEqualTo("THANK YOU");
assertThat(result.getCurrentBalance()).isEqualTo(10.0);
}
@Test
public void it_should_return_sold_out_when_out_of_stock() {
//Given
Integer id = 1;
Product product = Product.builder().id(1).name("name").price(5.0).stock(0).build();
ProductRequest productRequest = ProductRequest.builder().id(1).build();
//when
when(coinAmount.getBalance()).thenReturn(10.0);
when(productRepository.findById(id)).thenReturn(Optional.ofNullable(product));
ProductDispenseResponse result = productService.dispense(productRequest);
//Then
verify(productRepository).findById(id);
assertThat(result.getResponseMessage()).isEqualTo("SOLD OUT");
assertThat(result.getCurrentBalance()).isEqualTo(10.0);
}
@Test
public void it_should_return_unsufficient_message_when_balance_not_enough() {
//Given
Integer id = 1;
Product product = Product.builder().id(1).name("name").price(5.0).stock(3).build();
ProductRequest productRequest = ProductRequest.builder().id(1).build();
//when
when(coinAmount.getBalance()).thenReturn(1.0);
when(productRepository.findById(id)).thenReturn(Optional.ofNullable(product));
ProductDispenseResponse result = productService.dispense(productRequest);
//Then
verify(productRepository).findById(id);
assertThat(result.getResponseMessage()).isEqualTo("Unfortunately your balance is not sufficient.");
assertThat(result.getCurrentBalance()).isEqualTo(1.0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment