Unit-testing JDBI Mapper with ResultSet and StatementContext as parameters - java

I have to write a unit-test for the following method in class VPartnerExtMapper (VPartnerExtMapper.java):
import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.StatementContext;
import java.sql.ResultSet;
import java.sql.SQLException;
public class VPartnerExtMapper implements RowMapper<VPartnerExt> {
#Override
public VPartnerExt map(ResultSet rs, StatementContext ctx) throws SQLException {
int i = 1;
VPartnerExt result = new VPartnerExt();
result.setTecClient(rs.getLong(i++));
result.setPartnerId(rs.getLong(i++));
result.setTecVersionNr(rs.getLong(i++));
result.setName(rs.getString(i++));
return result;
}
}
My code for the unit-test so far (VPartnerExtMapperTest.java) :
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.sql.ResultSet;
import java.sql.SQLException;
#RunWith(JUnit4.class)
public class VPartnerExtMapperTest {
#Mock
private ResultSet resultSet;
#Mock
StatementContext ctx;
#Test
public void map() throws SQLException {
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.getString("NAME")).thenReturn("Michael");
VPartnerExt result = new VPartnerExtMapper().map(resultSet, ctx);
assertEquals("Michael", result.getName());
}
}
(Please let me know if I missed something and need to put it in the explanation before downgrading the question.)

Related

Powermock's Mock Static is not working as expected

For my project, I am working on power mock framework for unit testing.
I am facing an issue, I have mocked a static method, but still, it is calling the real method. I have set up the problem with simple classes. Please help to resolve the issue.
This is the Test that is being tested and it has a static method.
package in.service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
public static boolean getValue() throws SQLException {
Connection connection = DriverManager.getConnection("", "", "");
return connection == null;
}
}
This is the test class.
package in.service;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
#RunWith(PowerMockRunner.class)
#PrepareForTest({DriverManager.class})
public class ConnectionClassTest {
#Mock
private Connection connection;
#Before
public void setUp() {
PowerMockito.mockStatic(DriverManager.class);
}
#Test
public void check_Value_WhenConnectionIsNotPresent() throws SQLException {
when(DriverManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection);
ConnectionClass.getValue();
}
#Test
public void check_Value_WhenConnectionIsPresent() throws SQLException {
when(DriverManager.getConnection(anyString(), anyString(), anyString())).thenReturn(null);
ConnectionClass.getValue();
}
}
When I try to run these tests, DriverManager's actual connection method is called. Ideally, this method shouldn't be called.
Please help here if I am doing anything wrong here.

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());
}

Mockito - 0 Matchers Expected, 2 Recorded (InvalidUseOfMatchersException)

I referred to all available resources on Stackoverflow for similar queries. But I'm not sure what the issue with this test is:
It is throwing the following exception.
[main] ERROR com.example.dao.spring.TransactionDAOSpring - org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!0 matchers expected, 2 recorded.
Following is the code:
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyMapOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import com.example.dto.DisplayTwo;
import com.example.dto.DisplayOne;
import com.example.dto.DisplayThree;
public class TransactionDAOSpringTest {
TransactionDAOSpring transactionDAOSpring;
#Mock
DataSource dataSource;
#Mock
JdbcTemplate jdbcTemplate;
#Mock
SimpleJdbcCall storedProc;
#Rule
public ExpectedException thrown = ExpectedException.none();
private Map<String, Object> resultMap;
private List<DisplayOne> displayOne;
private List<DisplayTwo> displayTwo;
private List<DisplayThree> displayThree;
#Before
public void beforeMethod() {
MockitoAnnotations.initMocks(this);
transactionDAOSpring = new TransactionDAOSpring();
transactionDAOSpring.setJdbcTemplate(jdbcTemplate);
transactionDAOSpring.setDataSource(dataSource);
transactionDAOSpring.retrieveResultStoredProc = storedProc;
resultMap = new HashMap<String, Object>();
displayOne = new ArrayList<DisplayOne>();
displayTwo = new ArrayList<DisplayTwo>();
displayThree = new ArrayList<DisplayThree>();
}
#Test
public void testRetrieve_When_ResultSet_Not_Empty() {
displayOne.add(new DisplayOne());
displayTwo.add(new DisplayTwo());
displayThree.add(new DisplayThree());
resultMap.put("DisplayOneResultSet", displayOne);
resultMap.put("DisplayTwoResultSet", displayTwo);
resultMap.put("DisplayThreeResultSet", displayThree);
when(storedProc.execute(anyMapOf(String.class, Object.class)))
.thenReturn(resultMap);
Map<String, Object> returnedResultMap = transactionDAOSpring.retrieve(anyString(),
anyLong());
assertEquals(resultMap.size(), returnedResultMap.size());
}
Update: After debugging, it looks like it fails to getConnection from the dataSource and hence throws the exception.
Any help would be appreciated.
Matchers like anyString() or anyLong() can be used for mocking an object, for example inside when() or verify() invocation. In your case:
Map<String, Object> returnedResultMap = transactionDAOSpring.retrieve(
anyString(), anyLong());
is real method call. I think that is what causes InvalidUseOfMatchersException. Try invoking your method with stub values like empty string and 0L

How to mock Map with testng and powermockito

For personMap, I am setting the values with Powermockito;
But I am unable to get the values from map;
/**
*
*/
package mapmoocer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PersonStore {
Map<String, java.util.List<Person>> personMap = new HashMap<String, List<Person>>();
public void check() {
List<Person> list = personMap.get("RAM");
for(Person person : list) {
System.out.println(person);
}
}
public void hello() {
System.out.println("Hello");
}
}
Here, is the test class;
for test_check(), not able to cover for each block;
when(personMap.get("RAM")).thenReturn(value); always returning empty; even though I am setting the values for map;
/**
*
*/
package mapmoocer;
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.ArrayList;
import java.util.Map;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.modules.testng.PowerMockObjectFactory;
import org.testng.IObjectFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
public class PersonTest {
#InjectMocks
PersonStore personStore = new PersonStore();
#ObjectFactory
public IObjectFactory getObjectFactory() {
return new PowerMockObjectFactory();
}
#Mock
Map<String, java.util.List<Person>> personMap;
#BeforeClass
public void before(){
MockitoAnnotations.initMocks(this);
}
public void after() {
}
#Test
public void test_hello() {
personStore.hello();
}
#Test
public void test_check() {
Person person = new Person();
person.setEmail("aa");
java.util.List<Person> value = new ArrayList<Person>();
when(personMap.get("RAM")).thenReturn(value);
personStore.check();
}
}
Help me on this.
Why you want to mock a map? you can just create a new Map and assign it to your object. When we say Mock we Mock the action not the data.
We provide a mock is to make sure that the object we use will always provide a consistent value when we call one of its methods.
This will make us focus on the code we test, and don't need to worry about the method your code rely on will give you the wrong result.
So if you use a Map in your code, you just put the data in to the map, it's done. You don't need to mock it at all.
I am able to cover for-each snippet with the following code:
package mapmoocer;
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.ArrayList;
import java.util.Map;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.modules.testng.PowerMockObjectFactory;
import org.testng.Assert;
import org.testng.IObjectFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
public class PersonTest {
#InjectMocks
PersonStore personStore = new PersonStore();
#ObjectFactory
public IObjectFactory getObjectFactory() {
return new PowerMockObjectFactory();
}
#Mock
Map<String, java.util.List<Person>> personMap;
#BeforeClass
public void before(){
MockitoAnnotations.initMocks(this);
}
#AfterClass
public void after() {
}
#Test
public void test_hello() {
personStore.hello();
}
#Test(dataProvider="store")
public void test_check(Object data) {
java.util.List<Person> persons = (java.util.List<Person>)data;
when(personMap.get("RAM")).thenReturn(persons);
personStore.check();
}
public Object[][] store() {
Person person = new Person();
person.setEmail("aa");
person.setName("AA");
java.util.List<Person> value = new ArrayList<Person>();
value.add(person);
Object[][] result = {
{value}
};
return result;
}
}

Categories

Resources