0

How can i write Mockmvc test case for below code:

My controller class

@RestController

public class CartController {

@Autowired
private CartService cartService;

@GetMapping(path = "/addToCart", produces = MediaType.APPLICATION_JSON_VALUE)
public String cart(@Valid @RequestBody Cart cart) {
    return cartService.cart(cart);
}

}

My CartService class:

@Service

public class CartService {

private LoginRepository loginRepository;
@Autowired
private ProductRepository productRepository;
@Autowired
private CartRepository cartRepository;

@Autowired
private EmailService emailService;

public CartService(LoginRepository loginRepository) {
    this.loginRepository = loginRepository;
}

public String cart(Cart cart) {
    String username = cart.getUserName();
    System.out.println(username);
    String password = cart.getPassword();
    String email = cart.getEmail();

    if (loginRepository.existsByUserNameAndPassword(username, password)) {

        String productname = cart.getProductName();
        System.out.println(productname);
        String price = cart.getPrice();
        String discription = cart.getDiscription();

        if (productname != null) {

            if (productRepository.existsByProductNameAndPriceAndDiscription(productname, price, discription)) {
                Integer count = cartRepository.countByUserName(username);
                System.out.println(count);


                cartRepository.save(new Cart(username, password, email, productname, price, discription, count));
                return "{\"message\":\"product Successfully added to cart\"}";
            } else {
                throw new ResponseStatusException(
                        HttpStatus.NOT_FOUND, "entity not found"
                );
            }
        } else {

            throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
        }
    } else {

        throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }
}

I don't know how to write test case for above code using mockmvc. i don't know how can i write mockmvc test case for if else statement. so please help me how to write mockmvc test case for entire code so that i can do mockmvc test for if else statment also.

1 Answers1

0

I think you have a misunderstanding of what @WebMvcTest is used for. It is for Integration Testing a single slice of your Application – namely Web MVC. This means that your @WebMvcTest annotated Test should only use Mocks of your Service because what they should test is all the Web related stuff (proper conversion to JSON, XML; returning correct response codes, etc)

There is a tutorial on spring.io which should answer your questions.


For Testing your Service you can use plain old Unit Test with for example JUnit. In order for that to work you need to do some rework on your classes. First thing I would suggest is to replace the field injections with constructor injection. This is the recommended way of injection. Read here for more information.

After this change you can mock the dependencies of your Service (for example with Mockito) and pass them via the constructor. This way you can test the different if/else branches in your code.


And last but not least I would highly recommend to do some other rework on your service. Currently it returns information that are highly coupled to the Web context(the manually crafted JSON, the ResponseStatusException). The handling of those is the responsibility of your controller. Your Service should be independent of the thing (the controller in your case) that uses it. Just imagine your Service will be used by a other Class for a CLI Tool which does know nothing about JSON and response statuses.

Jan Schmitz
  • 1,181
  • 9
  • 13