Environment getProperty("SomeValue") value is coming null with Spring test and Mockito - java

I am writing JUnits for controller classes. I am using #PropertySource("classpath:webmvc_test.properties") and Environment object to read the values from properties file. On calling getProperty() method getting null value. The property file webmvc_test.properties is under the class path.
TestClass.java:
package com.kalavakuri.webmvc.web.controller;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.kalavakuri.webmvc.business.service.FamilyService;
import com.kalavakuri.webmvc.business.valueobject.FamilyAddress;
import com.kalavakuri.webmvc.business.valueobject.FamilyVO;
import com.kalavakuri.webmvc.init.ApplicationInitializer;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { ApplicationInitializer.class })
#PropertySource("classpath:webmvc_test.properties")
public class WelcomeControllerTest {
#Mock
private FamilyService familyService;
#InjectMocks
private WelcomeController welcomeController;
#Autowired
private Environment environment;
private MockMvc mockMvc;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(welcomeController).build();
}
#Test
public void welcomePage() throws Exception {
FamilyVO allFamilyMembers = getAllFamilyMembers();
when(familyService.getAllFamilyMembers()).thenReturn(allFamilyMembers);
mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("Index"));
}
/**
* #return
*/
private FamilyVO getAllFamilyMembers() {
FamilyVO allFamilyMembers = new FamilyVO();
FamilyVO familyVO = new FamilyVO();
familyVO.setFamilyId(Integer.parseInt(environment.getProperty("familyId")));
familyVO.setFamilyMemberName(environment.getProperty("familyMemberName"));
familyVO.setFamilyMemberAge(Integer.parseInt(environment.getProperty("familyMemberAge")));
FamilyAddress familyAddress = new FamilyAddress();
familyAddress.setAddress(environment.getProperty("familyAddress"));
familyVO.setFamilyAddress(familyAddress);
List<FamilyVO> familyVOs = new ArrayList<FamilyVO>();
familyVOs.add(familyVO);
allFamilyMembers.setFamilyVOs(familyVOs);
return allFamilyMembers;
}
}
webmvc_test.properties:
familyId=1
familyMemberName=Ramachandrappa Kalavakuri
familyMemberAge=36
familyAddress=Flat no: 305, 2nd Floor, Prakasa Pride Apartments, Opp To J.P.Morgan, Kadubesinahalli, Bangalore - 560087

I had the same problem and when I searched for a solution for it I found this article #Autowired + PowerMock: Fixing Some Spring Framework Misuse/Abuse it seems that there is a design problem between powermock and spring that prevent #Autowire from working correctly inside test classes, So instead of using #Autowire use #Mock and expect the returned values
package com.kalavakuri.webmvc.web.controller;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.kalavakuri.webmvc.business.service.FamilyService;
import com.kalavakuri.webmvc.business.valueobject.FamilyAddress;
import com.kalavakuri.webmvc.business.valueobject.FamilyVO;
import com.kalavakuri.webmvc.init.ApplicationInitializer;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { ApplicationInitializer.class })
#PropertySource("classpath:webmvc_test.properties")
public class WelcomeControllerTest {
#Mock
private FamilyService familyService;
#InjectMocks
private WelcomeController welcomeController;
#Mock
private Environment environment;
private MockMvc mockMvc;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(welcomeController).build();
when(environment.getProperty("familyId")).thenReturn("1");
when(environment.getProperty("familyMemberName")).thenReturn("Ramachandrappa Kalavakuri");
when(environment.getProperty("familyMemberAge")).thenReturn("36");
when(environment.getProperty("familyAddress")).thenReturn("Flat no: 305, 2nd Floor, Prakasa Pride Apartments, Opp To J.P.Morgan, Kadubesinahalli, Bangalore - 560087");
}
#Test
public void welcomePage() throws Exception {
FamilyVO allFamilyMembers = getAllFamilyMembers();
when(familyService.getAllFamilyMembers()).thenReturn(allFamilyMembers);
mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("Index"));
}
/**
* #return
*/
private FamilyVO getAllFamilyMembers() {
FamilyVO allFamilyMembers = new FamilyVO();
FamilyVO familyVO = new FamilyVO();
familyVO.setFamilyId(Integer.parseInt(environment.getProperty("familyId")));
familyVO.setFamilyMemberName(environment.getProperty("familyMemberName"));
familyVO.setFamilyMemberAge(Integer.parseInt(environment.getProperty("familyMemberAge")));
FamilyAddress familyAddress = new FamilyAddress();
familyAddress.setAddress(environment.getProperty("familyAddress"));
familyVO.setFamilyAddress(familyAddress);
List<FamilyVO> familyVOs = new ArrayList<FamilyVO>();
familyVOs.add(familyVO);
allFamilyMembers.setFamilyVOs(familyVOs);
return allFamilyMembers;
}
}

Related

NullPointer Mocking Kafka Results

I am writing tests and I was looking to mock the result of the kafka admin client, when a topic is created.
I am using Mockito to write my unit tests.
Here is the test code:
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.CreateTopicsResult;
import org.apache.kafka.clients.admin.ListTopicsResult;
import org.apache.kafka.common.KafkaFuture;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Mock;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.main.Launch;
import io.restassured.RestAssured;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.filter.log.ResponseLoggingFilter;
#QuarkusTest
public class AppTest {
#InjectMocks
private App mockApp;
#Mock
private Client mockClient;
#Mock
private Database mockDatabase;
#Mock
private Admin mockKafkaAdmin;
#Mock
private ListTopicsResult mockListTopicResult;
#Mock
private KafkaFuture<Set<String>> mockKafkaFuture;
#Mock
private KafkaFuture<Void> mockKafkaFutureVoid;
#Mock
private Set<String> mockSet;
#Mock
private CreateTopicsResult mockCreateTopicResult;
#Mock
private Map<String, KafkaFuture<Void>> mockKafkaTopicResult;
#BeforeAll
public static void setupAll() {
RestAssured.filters(new RequestLoggingFilter(), new ResponseLoggingFilter());
}
#BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
}
#Test
#Launch(value = {}, exitCode = 1)
public void testLaunchCommandFailed() {}
#Test
public void testCreateTopic() throws InterruptedException, ExecutionException {
Mockito.when(mockClient.getKafka()).thenReturn(mockKafkaAdmin);
Mockito.when(mockClient.getKafka().createTopics(Mockito.anyList())).thenReturn(mockCreateTopicResult);
Mockito.when(mockCreateTopicResult.values()).thenReturn(mockKafkaTopicResult);
Mockito.when(mockKafkaTopicResult.get("meme.transmit.test")).thenReturn(mockKafkaFutureVoid);
mockApp.createTopic("test");
Mockito.when(mockClient.getKafka().listTopics()).thenReturn(mockListTopicResult);
Mockito.when(mockClient.getKafka().listTopics().names()).thenReturn(mockKafkaFuture);
Mockito.when(mockClient.getKafka().listTopics().names().get()).thenReturn(mockSet);
Assertions.assertTrue(mockApp.containsTopic("test"));
}
// ...
}
I get a nullpointer error when this line is called in the production code:
Mockito.when(mockCreateTopicResult.values()).thenReturn(mockKafkaTopicResult);
But as you can see I mocked it with mockKafkaTopicResult. What might I be missing here? Also is there an easier method to work with KafkaAdminClient when writing unit tests?
Mockito.when(mockClient.getKafka().createTopics(Mockito.anyList()))
.thenReturn(mockCreateTopicResult);
The issue was that I was using anyList(), when the createTopics() only accepts Collections.
The fix: Mockito.anyCollections()

How to write unit test for clear all cache using cache manager

I have a method that evicts all the caches. PFB code for same:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import com.admin.AdminResponse;
#Service
public class CachingService {
private final static Logger logger = LoggerFactory.getLogger(CachingService.class);
#Autowired
protected CacheManager cacheManager;
public AdminResponse evictAllCaches() {
logger.info("Start - Clearing of cache");
cacheManager.getCacheNames().parallelStream()
.forEach(cacheName -> cacheManager.getCache(cacheName).clear());
AdminResponse adminResponse = new AdminResponse();
adminResponse.setMessage("ok");
logger.info("End - Clearing of cache");
return adminResponse;
}
}
Below is the unit test I'm trying to write:
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.admin.AdminResponse;
#ExtendWith(SpringExtension.class)
public class CachingServiceTest {
#InjectMocks
private CachingService testCachingService;
#Mock
protected CacheManager cacheManager;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testEvictAllCaches() {
AdminResponse adminResponse = testCachingService.evictAllCaches();
assertEquals("ok", adminResponse.getMessage());
}
}
I'm unable to understand how to write unit tests for code
cacheManager.getCacheNames().parallelStream()
.forEach(cacheName -> cacheManager.getCache(cacheName).clear());
Can someone please help? Thank you for your time!
You can write test code for Cache as follow:
#Test
public void testEvictAllCaches() {
Cache cache = Mockito.mock(Cache.class);
when(cacheManager.getCacheNames()).thenReturn(List.of("cacheName1", "cacheName2"));
Mockito.when(cacheManager.getCache(anyString())).thenReturn(cache);
AdminResponse adminResponse = testCachingService.evictAllCaches();
assertEquals("ok", adminResponse.getMessage());
}

Mock unit test a Service implementation that calls a Stored Procedure in Java

I’m trying to unit test a Service implementation that calls a Stored Procedure in Java.
My idea is to Mock or Stub the service just to see if all the calls are made correctly.
Not quite sure how to do this.
I’m using Springframework for the Service.
Any ideas on how to easily do this ? I'm getting null of course for the
#Autowired
private PerformanceService performanceService;
which doesn't initially happen, anyway I just want to Mock that and just make sure the calls are happening, thanks.
import com.integration.as400.entity.Performance;
import com.integration.as400.service.PerformanceService;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.BDDMockito.mock;
import static org.mockito.Mockito.when;
#Configuration
#RunWith(SpringRunner.class)
#SpringBootTest
#ContextConfiguration(classes={PerformanceService.class, TestConfiguration.class})
#ActiveProfiles("test")
public class PerformanceServiceImplMockTest {
private static final Logger logger = LoggerFactory.getLogger(PerformanceServiceImplMockTest.class);
#Autowired
private PerformanceService performanceService;
#Before
public void setupMock(){
MockitoAnnotations.initMocks(this);
performanceService = mock(PerformanceService.class);
}
#Test
public void shouldReturnListPerformance_whenGetListPerformanceIsCalled() throws Exception{
List<Performance> performances = new ArrayList<>();
performances.add(new Performance("0000184","00001","MWR","SI",LocalDate.parse("2016-01-01"),LocalDate.parse("2016-01-31"),"CAD",48585.63,34821.01,47501.47,-94372.00,11184.70,10.000322,"",33105.91));
performances.add(new Performance("0000184","00001","MWR","SI",LocalDate.parse("2016-01-01"),LocalDate.parse("2016-01-31"),"CAD",142743.11,260376.38,41688.49,-4886.00,11184.70,35937.14,"",7.475078));
logger.info("Stubbing getListPerformance(int pageNumber, String loadStartDate, String loadEndDate) to return " + performances);
// Arrange
when(performanceService.getListPerformance(2, "2021-08-01", "2021-08-31")).thenReturn(performances);
// Act
List<Performance> retrievedPerformances = performanceService.getListPerformance(2, "2021-08-01", "2021-08-31");
// Assert
assertThat(retrievedPerformances, is(equalTo(performances)));
}
}

JUnit Testing FaceContext and Session Code

I am attempting to Junit test (IDE: Intellij) Method inside a class called "ManagementDashboardBean" called: (Method name): init()
The method contains FaceContext and Session. I tried the following: https://codenotfound.com/mockito-unit-testing-facescontext-powermock-junit.html
but am still running into issues. I am using Mockito and PowerMockito to help but cannot figure out my init() is saying Null Pointer Exception (NPE). Any guidance would be greatly appreciated. Thanks
P.S the end goal is to show proper test code coverage of this method.
public void init() {
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession)context.getExternalContext().getSession(false);
userInfo = (UserSessionInfo)session.getAttribute(ConstantsUtil.USER_INFO);
startDt = FDUtil.toDate(FDUtil.toStartOfMonth(userInfo.getCurrentDateMillis()));
endDt = FDUtil.toDate(FDUtil.toEndOfMonth(userInfo.getCurrentDateMillis()));
autoCompleteDate = false;
}
Current JUnit Test
package view.managed.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import com.sun.jdi.connect.Connector;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest({FacesContext.class})
public class ManagementDashboardBeanTest {
private ManagementDashboardBean someBean;
#Mock
private FacesContext facesContext;
#Mock
private ExternalContext externalContext;
#Before
public void setUp() throws Exception {
someBean = new ManagementDashboardBean();
//mock all static methods of FaceContext using PowerMockito
PowerMockito.mockStatic(FacesContext.class);
when(FacesContext.getCurrentInstance()).thenReturn(facesContext);
when(facesContext.getExternalContext()).thenReturn(externalContext);
}
#Test
public void testInitContext() {
//create Captor instances for the userInfo
// ArgumentCaptor<String> clientIdCapture = ArgumentCaptor.forClass(String.class);
// ArgumentCaptor<HttpSession> session = ArgumentCaptor.forClass(HttpSession.class);
// Run the method being tested
// someBean.init();
// verify(facesContext).addMessage(clientIdCapture.capture(), (FacesMessage) session.capture());
}
}
The actual .java source file starts with:
public class ManagementDashboardBean extends EntityManagerService implements Serializable {
private static final Logger LOG = LoggerFactory.getLogger(ManagementDashboardBean.class);
The right after is this, which confuses the hell out of me:
public ManagementDashboardBean() {
init();
}
What I have added so far:
import static org.junit.Assert.*;
import javax.faces.context.FacesContext;
import mil.af.fd.view.managed.services.EntityManagerService;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareForTest;
import java.io.Serializable;
#RunWith(MockitoJUnitRunner.class)
#PrepareForTest({FacesContext.class})
public class ManagementDashboardBeanTest {
private ManagementDashboardBean dashboard;
private Serializable serializableMock;
private EntityManagerService entityManagerServiceMock;
#BeforeClass
public static void before() {
System.out.println("Before Class");
}
#Before
public void setUp() throws Exception {
entityManagerServiceMock = Mockito.mock(EntityManagerService.class);
serializableMock = Mockito.mock(Serializable.class);
dashboard = new ManagementDashboardBean(serializableMock);
}
#Test
public void testInitContext() {
// dashboard.init();
System.out.println("Test 1");
}
}

How to test DELETE method in Spring boot using Mockito and JUnit

In Spring boot framework, I'm finding a difficulty with the controller Unit testing using JUnit and Mockito. I want to test this method. How to test DELETE Request method:
// delete application
Controller class
#DeleteMapping("/applications")
public String deleteApplicationByObject(#RequestBody Application application) {
applicationService.deleteById(application.getId());
return "Deleted";
}
// delete application
Service class
#Override
#Transactional
public String removeById(Long id) {
dao.deleteById(id);
return "SUCCESS";
}
// delete application
Dao class
#Override
public void deleteById(Long id) {
Application application = findById(id);
em.remove(application);
}
Thank you in advance.
After a while i'm able to find a solution of my question which is,
ApplicationControllerTest.class
package com.spring.addapplication.test.controller;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.addapplication.controller.ApplicationController;
import com.spring.addapplication.model.Application;
import com.spring.addapplication.service.ApplicationService;
import com.spring.addapplication.url.UrlChecker;
#RunWith(SpringJUnit4ClassRunner.class)
public class ApplicationControllerTest {
#Mock
ApplicationService applicationService;
private MockMvc mockMvc;
#Before
public void setUp() throws Exception {
initMocks(this);// this is needed for inititalization of mocks, if you use #Mock
ApplicationController controller = new ApplicationController(applicationService,urlChecker);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
#Test
public void deleteApplication() throws Exception {
Mockito.when(applicationService.removeById(10001L)).thenReturn("SUCCESS");
mockMvc.perform(MockMvcRequestBuilders.delete("/applications", 10001L))
.andExpect(status().isOk());
}

Categories

Resources