Testing functions in spring boot which have autowired dependencies - spring-boot

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.

Related

Can this method be tested using mockito?

I am not sure how to test the first method in the service layer with Mockito as it is using the helper method. Below is my failed attempt at a test: I get an InvalidUseOfMatchersException in the second when clause.
Thanks in advance!
#Mock
private EntityRepository EntityRepo;
#InjectMocks
private EntityService EntityService;
public List<DTO> getAllDTOs(){
//first method
return entityRepo.findAll()
.stream()
.map(this::convertEntityToDTO)
.collect(Collectors.toList());
}
//helper method
public DTO convertEntityToDTO(Entity entity) {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration()
.setMatchingStrategy(MatchingStrategies.LOOSE);
DTO dto = new DTO();
dto = modelMapper.map(entity, DTO.class);
return dto;
}
#Test
public void EntityService_GetAll_ReturnsDTOList() {
when(entityRepo.findAll()).thenReturn(Mockito.anyList());
//the second when clause: when(entityService.convertEntityToDTO(Mockito.any(Entity.class)))
.thenReturn(Mockito.any(DTO.class));
List<DTO>DTOList = entityService.getAllDTOs();
Assertions.assertThat(DTOList).isNotNull();
Mockito#any* methods are actually defined in class ArgumentMatchers and can only be used to match the call arguments when setting up a mock or when verifying calls. All matcher methods return null (but have side-effects of modifying a matcher stack to be able to properly detect and match mocked calls).
For instance, you might do Mockito.when(svc.print(Mockito.anyString()).doNothing() when you don't care about the input or Mockito.verify(svc.print(Mockito.anyString()), Mockito.never()) when you want to verify that the method has never been called.
When setting up your mock, you have to provide a real value in your thenReturn call:
when(entityRepo.findAll()).thenReturn(Collections.emptyList());
when(entityService.convertEntityToDTO(Mockito.any(Entity.class)))
.thenReturn(new DTO());

Spring MVC Unit Testing - Mocked Service method is not called

I was working on a spring boot project where I have controller which calls a service method and process the output.
I'am using spring MockMvc for testing the web layer. In my test class I have mocked the service method with Mockito.when(). But when I call the corresponding handler method it is not calling the mocked service method instead returns a null response.
Controller
#Controller
public class SocialLoginEndpoints {
#Autowired
#Qualifier("facebookAuth")
SocialLogin faceBookAuth;
#Autowired
#Qualifier("googleAuth")
SocialLogin googleAuth;
#Autowired SignupService signupService;
#GetMapping("/auth/google")
public String googleAuth(#RequestParam String signupType, HttpServletRequest request) {
return "redirect:" + googleAuth.getAuthURL(request, signupType);
}
}
Test Class
#WebMvcTest(SocialLoginEndpoints.class)
class SocialLoginEndpointsTest {
#Autowired MockMvc mockMvc;
MockHttpServletRequest mockHttpServletRequest;
#MockBean GoogleAuth googleAuth;
#MockBean FacebookAuth facebokAuth;
#MockBean SignupService signupService;
#BeforeEach
void setUp() {
mockHttpServletRequest = new MockHttpServletRequest();
}
#Test
void googleAuth() throws Exception {
Mockito.when(googleAuth.getAuthURL(mockHttpServletRequest, "free"))
.thenReturn("www.google.com");
mockMvc
.perform(MockMvcRequestBuilders.get("/auth/google").param("signupType", "free"))
.andExpect(MockMvcResultMatchers.redirectedUrl("www.google.com"))
.andExpect(MockMvcResultMatchers.status().isFound())
.andDo(MockMvcResultHandlers.print());
Mockito.verify(googleAuth, Mockito.times(1)).getAuthURL(mockHttpServletRequest, "free");
}
The reponse which is returned is
MockHttpServletResponse:
Status = 302
Error message = null
Headers = [Content-Language:"en", Location:"null"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
please help me to resolve this issue.
Thanks in Advance !
You stubbed googleAuth.getAuthURL incorrectly.
The MockHttpServletRequest you create in your test and use during stubbing is not the same instance as HttpServletRequest that is sent via MockMvc. Also, they are not equal to each other (Object.equals is used as it is not overriden)
By default Mockito uses equals to verify if arguments in a stubbing match those in the real call. Your stubbing params do not match call params, thus a default value for the method (null) is returned.
The simplest way to fix is to relax argument matchers.
Mockito.when(googleAuth.getAuthURL(
any(HttpServletRequest.class),
eq("free")))
.thenReturn("www.google.com");

how to write Test case for if else using mockMvc in 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.

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))

How to replace a constructor injected object with mocked object in spock

I know that the question is very big but I just want to clear the situation i am into.
I am working on an application that consumes the JMS messages from the message broker.
We are using camel route on the consumer side. All the object required in route builder are injected through constructor injection using spring .
I want to mock the behavior of the actual processing, Once the consumer receives the message from the queue. All the classes gets loaded via the spring configuration.
Below are the three classes:
CustomRouteBuilder.java
public CustomRouteBuilder extends RouteBuilder{
private CustomRouteAdapter customAdapter;
public CustomRouteBuilder (CustomRouteAdapter customAdapter){
this.customAdapter = customAdapter
}
public void configure(RouteDefinition route){
route.bean(customAdapter);
}
}
CustomRouteAdapter.java
public class CustomRouteAdapter {
private Orchestrator orchestrator;
public CustomRouteAdapter (Orchestrator orchestrator){
this.orchestrator = orchestrator;
}
#Handler
public void process(String message){
orchestrator.generate(message) ;
}
}
Orchestrator.java
public class Orchestrator{
private Service service;
public Orchestrator(Service service){
this.service = service;
}
public void generateData(String message){
service.process(message);
}
}
As per our requirement we have to load this configuration file and then write the functional test using spock.
Below is my
CustomRouteBuilderTest.groovy file.
import org.springframework.test.util.ReflectionTestUtils
import spock.lang.Specification
#ContextConfiguration(classes=[CustomRouteBuilderTest.Config.class])
class CustomRouteBuilderTest extends Specification{
private static final String message = "Hello";
Orchestrator orchestrator;
#Autowired
CustomRouteAdapter customRouteAdapter;
def setup(){
orchestrator = Mock(Orchestrator)
ReflectionTestUtils.setField(customRouteAdapter,"orchestrator",orchestrator)
orchestrator.generate(message )
}
private String getMessageAsJson() {
//return json string;
}
private String getMessage() {
// return message;
}
private Map<String, Object> doMakeHeaders() {
//Create message headers
}
private void doSendMessage(){
Thread.sleep(5000)
Map<String,Object> messageHeader = doMakeHeaders()
byte [] message = getMessageAsJson().getBytes()
CamelContext context = new DefaultCamelContext()
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(jmsBrokerUrl)
context.addComponent("activeMQComponent",JmsComponent.jmsComponent(connectionFactory))
ProducerTemplate template = context.createProducerTemplate()
context.start();
template.sendBodyAndHeaders("queueName", message, messageHeader)
}
def "test message consumption"(){
given:
doSendMessage()
}
#Configuration
#Import([FunctionalTestCommonConfig.class,CustomRouteBuilderConfig.class])
#PropertySource(value="classpath:test.properties")
static class Config{
}
}
The problem that here is even though I inject the mocked object to the adapter using ReflectionTestUtils , I am not able to define its behavior correctly.
And when the message is received the orchestrator tries to process it.
My Requirement is that:
Adapter should be called from the camel route automatically which happens but
when the orechestrator.generate is called from the adapter then nothing should happen it should simply return.
But here nothing like that is going on.
Each time I send a message the consumer(RouteBuilder) receives it and calls the handler function which then calls the
orchestrator.generate(message)
function and the orchestrator starts processing and throws an exception from service level.
Any one can please help me on this.
I suppose your beans have been proxified by Spring, and this proxy use cglib (because you see CustomRouteBuilder$$EnhancerBySpringCGLIB$$ad2783ae).
If it's really the case, you didn't #Autowired in your test the real instance of your CustomRouteAdapter but a cglib proxy: Spring creates a new class, extending the realclass, and overriding all the methods of this class. The new method delegate to the real instance.
When you change the orchestrator field, you are in reality changing the orchestrator field of the proxy, which is not used by the real instance.
There are severals ways to achieve what you want to do:
add a setOrchestrator method in CustomRouteAdapter
create the mock in your spring configuration and let spring inject this mock instead of a real instance of Orchestrator
Inject the orchestrator in the real instance (ugly - I didn't recommend you that, it didn't help in the testability of your code!)
customRouteAdapter.targetSource.target.orchestrator = _themock_

Resources