When testing REST api i get a 200OK when i should get 403

Viewed 58

I'm writing some tests for my rest API and this is the controller I'm using this post:

@PostMapping
    public ResponseEntity<?> add(@RequestBody @Valid Product product) {
        List<Product> recentProduct = productService.findAllRecent();
        for(Product p : recentProduct){
            if(p.getName().equals(product.getName()) && p.getId() == product.getId()){
                return new ResponseEntity<Void>(HttpStatus.FORBIDDEN);
            }
        }
            productService.add(product);
            return new ResponseEntity<Void>(HttpStatus.OK);
    }

This is my test:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc   
public class ProductControllerTest {
   @Autowired
   private TestRestTemplate restTemplate;
   @MockBean
   private ProductRepository productRepository;
   @Autowired
   private MockMvc mockMvc;
   @Autowired
   ProductController productController;
   @Autowired
   ProductService productService;

   @Test
   void testAddOnceShouldReturn201() {

       Product product = new Product(1, "TestSameName", LocalDateTime.now());
       
       productController.add(product);
       Assertions.assertTrue(productController.add(product).getStatusCode().is2xxSuccessful());
   }

   @Test
   void testAddTwiceRecentShouldReturn403() {
       Product product = new Product(1, "TestName", LocalDateTime.now());
       Product product2 = new Product(1, "TestName", LocalDateTime.now());
       productController.add(product);
       ResponseEntity<String> response = restTemplate.postForEntity("/v1/products", product,String.class);
       productController.add(product2);
       ResponseEntity<String> response2 = restTemplate.postForEntity("/v1/products", product2,String.class);
       Assertions.assertTrue(response2.getStatusCode().is4xxClientError());
   }
...

So my findAllRecent fetches recently added data to my database. I than create a list and i check against it to see if the new addition is found there, I think the problem resides in that part, for some reason my list might be coming empty or something, i add two equal products even id because I don't have any restraints on that. So I'm getting a 200ok when i should be getting a 403.

Any tips and help is apreciated. Thanks in advance.

[Edit] I should add if i post the requests manually on postman or through curl i get the desired behavior. Added entire Test class as requested.

[Edit 157] I'm using H2 as a database.I'm not sure if that would matter since I'm adding both products at the same time and both should be in memory.

0 Answers
Related