how to write Test case for if else using mockMvc in spring boot - spring-boot

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.

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.

Related

Testing functions in spring boot which have autowired dependencies

Here is a minimal version of code that I want to test:
#Service
public class Ver {
#Autowired
private DHClient dhclient;
#Autowired
private DHUrlService dhUrlService;
public String getLVersion(String LRversion)
{
String vers=dhclient.get(dhUrlService.getUrl());
return getVersion(vers, LRversion);
}
}
Now the problem with testing this is that. dhclient is autowired inside the Ver class.
The get function makes an HTTP Get request and fetches a response.
I want the test case to actually make the dhclient.get call and return the result.
Any ideas on how to go about testing this?
How do I test that getLVer(String lrVersion) returns null when "test" is passed as the argument?
#Service
public class DHClient {
#Value("${clientId}")
private String clientId;
private HttpClient httpClient;
public String get(String URL){
HttpRequest request// build the HTTP request
HttpResponse<String> response = httpCient.send(request,HttpResponse.BodyHandlers.ofString());
return response.body()
}
}
the above is the code of the DHClient. Since I want to make an actual GET call using the get function. Probably mocking the object is not a good idea. The alternative would be to create an actual object. But this has fields like clientId and httpClient which are initialized by Spring. I am not sure how to create an actual object for this.

Dependency injection with mockito example

I am very new with Mockito and I don't get the following example (classes were provided, only test to write) and how to solve it.
What I try to do is use a test double for the supplier so that we can control the returned greeting in the test and assert that the GreetingService does not modify the greeting message in any way. Then assert that the returned greeting string is equal to "Hello Andy.".
public class Greeting {
private final String template;
public Greeting(String template) {
this.template = template;
}
public String forName(String world) {
return String.format(template, world);
}
}
#Component
public class GreetingService {
private final Supplier<Greeting> greetingSupplier;
public GreetingService(Supplier<Greeting> greetingSupplier) {
this.greetingSupplier = greetingSupplier;
}
public String greet(String name) {
return greetingSupplier.get().forName(name);
}
}
#Component
public class RandomGreetingSupplier implements Supplier<Greeting> {
private final List<Greeting> greetings = Arrays.asList(
new Greeting("Hello %s."),
new Greeting("Hi %s!"),
);
private final Random random = new Random();
#Override
public Greeting get() {
return greetings.get(random.nextInt(greetings.size()));
}
}
#SpringBootTest
public class GreetingServiceTest {
#Autowired
GreetingService greetingService;
#MockBean
Supplier<Greeting> greetingSupplier;
#Test
void getGreetingForPerson() {
String name = "Andy";
// that test cannot know which greeting will be returned by the supplier
// WHY IS IT NULLPOINTEREXCEPTION AFTER INITIALIZING #MockBean
//String greeting = greetingService.greet(name);
//assertThat(greeting).contains(name);
// WROTE SUCH TEST HERE -> NullPointerException WHY?
Mockito.when(greetingSupplier.get().forName(name)).thenReturn("Hello %s.");
assertThat(greetingSupplier.equals("Hello Andy."));
// THIS IS WORKING & TEST PASSED BUT I GUESS ITS WRONG?
Mockito.when(greetingSupplier.get()).thenReturn(new Greeting("Hello %s."));
assertThat(greetingSupplier.equals("Hello Andy."));
}
}
Mockito.when(greetingSupplier.get().forName(name)).thenReturn("Hello %s.");
You can't chain calls like that, you need to produce intermediate results, like
Supplier<Greeting> supplier = mock(Supplier.class);
Mockito.when(supplier).forName().thenReturn("Hello %s.");
Mockito.when(greetingSupplier.get()).thenReturn(supplier);
For dependency injection, you need to create the subject under test with the mocked Supplier. You can do that in a #Before method for example.
Your mocking is wrong.
Mockito.when(greetingSupplier.get().forName(name)).thenReturn("Hello %s.");
You mocked Supplier<Greeting> and the default behavior is to return null. So when you call greetingSupplier.get() in your first line it returns null. You directly chain forName which nou basicall is null.forName which leads to an error.
Your second part is actually (kind of) correct.
Mockito.when(greetingSupplier.get()).thenReturn(new Greeting("Hello %s."));
You now properly return a response from greetingSupplier.get(). Instead of chaining the call.
However I would argue that your excercise is wrong. Why? When using a Supplier<?> in Spring it actually is a lazy beanFactory.getBean call. You can lazily inject dependencies this way. You should have a mock for Greeting which returns a hardcoded String which you can check.

How to mock beans Autowired on service layer in #WebMvcTest

I am testing a REST API's in Spring boot gradle app, my mocked service using #MockBean is returning null. This mocked service return null if there are some beans Autowired in service class(I used constructor injection).
Here is sample Code(Not compiled, only for understanding)
#RestController
#RequestMapping("/xxx")
class TestController {
private RetriveDataService retriveDataService;
public TestControllerx(RetriveDataService retriveDataService) {
this.retriveDataService = retriveDataService;
}
#PostMapping(value = "/yyy")
public MyResponseModel myMethod(#RequestBody MyRequestModel model) {
return retriveDataService.retriveData(model);
}
}
#Service
class RetriveDataService {
private TokenService tokenService;
public RetriveDataService(TokenService tokenService) {
this.tokenService = tokenService;
}
public MyResponseModel retriveData(MyRequestModel model) {
String accessToken = tokenService.getToken().getAccessToken();
return retriveData(model, accessToken);
}
}
#RunWith(SpringRunner.class)
#WebMvcTest(TestController.class)
public class TestControllerTest {
#Autowired
private MockMvc mvc;
#Autowired
private ObjectMapper objectMapper;
#MockBean
private RetriveDataService retriveDataService;
#Test
public void testRetriveData() throws Exception {
mvc.perform(MockMvcRequestBuilders.post("/xxx/yyy").content(objectMapper.writeValueAsString(new MyRequestModel()))
.contentType(MediaType.APPLICATION_JSON_UTF8)).andDo(MockMvcResultHandlers.print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
}
When I run this test, i am getting following output(If my service do not need another bean, I am getting expected output)
MockHttpServletResponse:
Status = 200
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Due to this response i facing problem on line .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));. also when i check response body(as body is also a null)
Sample project to reproduce the issue is here
Checking your repository confirmed assumption form the discussion in comments under question.
You specify expectations on your mock
MyModel requestMessage = new MyModel();
requestMessage.setMessage("Hello Request Post");
given(testService1.getMessage(requestMessage)).willReturn(responseMessage);
but the message received to in your controller in your #WebMvcTest is not equal to requestMessage specified in the test. This is due to the fact that MyModel class does not override equals method.
In this situation, Mockito will use its default behaviour:
By default, for all methods that return a value, a mock will return either null, a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.
You have two options to fix the problem:
override equals (and hashCode) in your request class.
Get acquainted with argument matchers
More info on option 2.:
Technically, your expectation is equivalent to:
given(testService1.getMessage(ArgumentMatchers.eq(requestMessage)))
.willReturn(responseMessage);
You can use other matcher, or even define your own. This is useful if you cannot modify code of your argument's type (type coming from 3-rd party library etc).
For example, you can use ArgumentMatchers.any(MyModel.class))

Spring 5 Webflux functional endpoints - How to perform input validation?

According to the current doc (5.0.0.RELEASE) Spring Webflux supports validation when working with annotated controllers:
By default if Bean Validation is present on the classpath — e.g.
Hibernate Validator, the LocalValidatorFactoryBean is registered as a
global Validator for use with #Valid and Validated on #Controller
method arguments.
However nothing is said about how to automate it with functional endpoints. In fact, the only example of input processing in the documentation doesn't validate anything:
public Mono<ServerResponse> createPerson(ServerRequest request) {
Mono<Person> person = request.bodyToMono(Person.class);
return ServerResponse.ok().build(repository.savePerson(person));
}
Are we supposed to do this manually or there is some automatic way to do it?
In Spring version 5.0, there is no automatic way to do validation in functional endpoints, and as such validation must be done manually.
Though there are currently no concrete plans to do so, we might add some sort of validation in the future. But even then it will be an explicit method call, and not an automatic mechanism. Overall, the functional endpoint model is designed to be a lot more explicit than the annotation-based model.
As arjen-poutsma said, it seems there is no way of running automated validations on Spring 5 functional endpoints.
Spring documentation is not very clear about this, and it doesn't suggest any approach.
On this Baeldung article, you'll find an idea on how you can run validations using this approach (disclaimer: I'm the writer of the article :) )
In a nutshell, you can follow these steps:
Implement Spring Validators to evaluate your resources
Create an abstract class with the basic procedure that any handler will follow when processing a request, leaving up to the children classes what to do when the data is valid
Make your request handler classes extend this abstract class, implementing this abstract method, stating the body it will be expecting, and what validator needs to be used to validate it
EDIT:
I've been following this related Spring issue, and it seems we now count with official documentation regarding this subject: https://github.com/spring-projects/spring-framework/blob/master/src/docs/asciidoc/web/webflux-functional.adoc#validation
The suggested approach is to use validators as explained in the article.
At the current version(2.0.4.RELEASE) there isn't a way to do automatic validation with handles, however you always could make a manual validation like this:
#Slf4j
#Component
#FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
#RequiredArgsConstructor
public class MyHandlerValidator implements HandlerValidator<MyResource> {
Validator validator;
#Override
public void callValidator(final MyResource fdr) {
final DataBinder binder = new DataBinder(fdr);
binder.setValidator(validator);
binder.validate();
if (binder.getBindingResult().hasErrors()) {
final String reason = binder.getBindingResult().getFieldError().toString();
log.error(reason);
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, reason);
}
}
}
The thing with this, its that the you should throw a WebExchangeBindException like automatic validation does, however i could't create a MethodParameter witch is a dependency to create this exception.
UPDATE:
Spring show us a way to do it, which is similar to my solution, but, not enough in my opinion on documentation
Just to demo some working code. If you need simple validation based on the object annotations like:
#Value
#Builder
#Jacksonized
public class SigninRequest {
#NotBlank(message = "The username is mandatory")
#Email(message = "The username should be valid Email")
String username;
#NotBlank(message = "The password is mandatory")
String password;
}
At the handler you need just one simple additional operator doOnNext:
#Component
#RequiredArgsConstructor
public class AuthHandler {
private final AuthService authService;
private final ObjectValidator validator;
public Mono<ServerResponse> signin(ServerRequest request) {
return ok().body(
request.bodyToMono(SigninRequest.class)
.doOnNext(validator::validate) //<-- just one single line
.flatMap(login -> authService.authenticate(login.getUsername(), login.getPassword())),
AuthResult.class);
}
}
The ObjectValidator is doing actual validation and throws the runtime exception with the 4xx error in case of validation errors:
#Component
#RequiredArgsConstructor
public class ObjectValidator {
private final Validator validator;
public <T> T validate(T object) {
var errors = validator.validate(object);
if (errors.isEmpty()) {
return object;
} else {
String errorDetails = errors.stream().map(er -> er.getMessage()).collect(Collectors.joining(", "));
throw new ObjectValidationException(errorDetails);
}
}
}
And the exception:
#ResponseStatus(code = HttpStatus.UNPROCESSABLE_ENTITY)
public class ObjectValidationException extends RuntimeException {
public ObjectValidationException(String errorDetails) {
super("Please supply the valid data: " + errorDetails);
}
}
If you properly setup global error handling you can keep you handler code clean and reuse the object validator across all your handlers.

Exception while getting values from Mocked object using Mockito

I am writing junit using mockito for a Spring #component class.
When it try to access the static field from final constant file throwing Null pointer exception.
CruserDomainTest
#RunWith(MockitoJUnitRunner.class)
public class CruserTest {
#InjectMocks
CruserDomain eDomain = new CruserDomain();
#Test
public void testGetCruseById() throws Exception,
{
String cCode = "AA";
int employeeId = 21305;
when(
cruseRepository.getTestId(
anyString(), anyInt())).thenReturn(
buildAndReturnList());
when(
payDomain.getRefPay(anyString(),
anyString(), anyString(), anyString()))
.thenReturn(buildPay());
CruseMember expectedResponse = eDomain.getMemberById(
airlineCode, employeeId);
}
CruserDomain
//getting null pointer exception in the below line execution
//while getting the current month
public CruseMember getMemberById(String cCode, int employeeId)
throws Exception {
//Some code //
if (contractMonth.getType().equals(
CruseConstant.CURRENT_MONTH)) {
currentMonthStartDate = cMonth.getStartDate();
} else if (contractMonth.getType().equals(
CruseConstant.OTHER_MONTH)) {
nextMonthStartDate = cMonth.getStartDate();
}
CruseConstant:
public final class CruseConstant {
public static final String CURRENT_MONTH = "C";
public static final String OTHER_MONTH = "O";
}
I tried with ReflectionTestutils but throwing exception while junit starts.
Help me on how to lookup final class static variables in the injectMocked class.
I strongly advise you to not mock domain objects, instead I would craft builders that can generate those objects.
Also in the code snippet #InjectMocks has no mock to inject, so injects nothing, mock fields should be declared in the test class. However I stress the point of not mocking the domain !
We've written this page on how to write good tests, I think TDD practitioners should read it, wether they use mockito or not. Lot of people contributed to refine this wiki page.
=> https://github.com/mockito/mockito/wiki/How-to-write-good-tests
It is really hard to understand your code because you have replaced the interesting parts with comments, but I would guess that you get a NPE because
contractMonth
is null. That is because you did not mock and/or forgot to define the behaviour of the class that you get the contractMonth from (CruserRepository?)

Resources