Skip to content

Instantly share code, notes, and snippets.

@atesibrahim
Last active June 30, 2022 13:22
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/cb186a915f0c3cfcc133c6062b9552c0 to your computer and use it in GitHub Desktop.
Save atesibrahim/cb186a915f0c3cfcc133c6062b9552c0 to your computer and use it in GitHub Desktop.
@ExtendWith(SpringExtension.class)
class ProductControllerTest {
@InjectMocks
private ProductController productController;
@Mock
private ProductService productService;
private MockMvc mockMvc;
private final ObjectMapper objectMapper = new ObjectMapper();
@BeforeEach
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(productController).build();
}
@Test
public void it_should_test_when_product_id_is_valid() throws Exception {
//given
ProductRequest productRequest = ProductRequest.builder().id(1).build();
ArgumentCaptor<ProductRequest> argumentCaptor = ArgumentCaptor.forClass(ProductRequest.class);
//when
ResultActions result = mockMvc.perform(post("/products")
.content(objectMapper.writeValueAsString(productRequest))
.contentType(MediaType.APPLICATION_JSON));
//then
verify(productService).dispense(argumentCaptor.capture());
result.andExpect(status().isOk());
}
@Test
public void it_should_test_when_product_id_is_not_valid() throws Exception {
//given
ProductRequest productRequest = ProductRequest.builder().id(0).build();
//when
ResultActions result = mockMvc.perform(post("/products")
.content(objectMapper.writeValueAsString(productRequest))
.contentType(MediaType.APPLICATION_JSON));
//then
verifyNoInteractions(productService);
result.andExpect(status().isBadRequest());
}
@Test
public void it_should_test_when_product_id_is_null() throws Exception {
//given
ProductRequest productRequest = ProductRequest.builder().build();
//when
ResultActions result = mockMvc.perform(post("/products")
.content(objectMapper.writeValueAsString(productRequest))
.contentType(MediaType.APPLICATION_JSON));
//then
verifyNoInteractions(productService);
result.andExpect(status().isBadRequest());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment