Object is not getting mocked. Throwing Null Pointer Exception - java

I am running my code with mockito framework. Framework is creating mocked object for One Implementation and not creating any mock object for other object due to that it is throwing null pointer exceptions. Here is my code and output:
package com.sohi;
import java.io.IOException;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.HTablePool;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
public class HbaseExample {
private HTablePool pool;
private static final String HTABLE_NAME = "table1";
public String getValue(String rowKey, String columnFamily, String columnName) throws IOException {
HTableInterface table = pool.getTable(HTABLE_NAME);
Get get = new Get(Bytes.toBytes(rowKey)).addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(columnName));
System.out.println("Is table Null ? " + (table == null));
Result result = table.get(get);
System.out.println("is result null ? " + (result == null));
byte [] val = result.value();
return Bytes.toString(val);
}
}
My Mockito Test class is :
import static org.junit.Assert.*;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.HTablePool;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.sohi.HbaseExample;
#RunWith(MockitoJUnitRunner.class)
public class HbaseExampleTest {
#Mock
HTablePool pool;
#Mock
HTable hTable;
#Mock
Result result;
#InjectMocks
HbaseExample hbase = new HbaseExample();
private static final String HTABLE_NAME = "table1";
private static final String ROW_KEY = "k1";
private static final String COLUMN_FAMILY = "col1";
private static final String COLUMN_NAME = "c1";
private static final String CELL_VALUE = "v1";
#Test
public void test1() throws Exception {
Get get1 = new Get(Bytes.toBytes(ROW_KEY)).addColumn(Bytes.toBytes(COLUMN_FAMILY), Bytes.toBytes(COLUMN_NAME));
Mockito.when(pool.getTable(HTABLE_NAME)).thenReturn(hTable);
Mockito.when(hTable.get(get1)).thenReturn(result);
Mockito.when(result.value()).thenReturn(Bytes.toBytes(CELL_VALUE));
String str = hbase.getValue(ROW_KEY, COLUMN_FAMILY, COLUMN_NAME);
assertEquals(str, CELL_VALUE);
}
}
Output is :
Is table Null ? false
is result null ? true
And Also throwing null pointer exception near result.value().
only table object is getting mocked.

The problem is here:
Mockito.when(hTable.get(get1)).thenReturn(result);
This does not match your actual call, because your get1 is not equal to the Get object that is actually passed. (It looks the same, but Get does not override equals() and so uses the default behaviour of treating any two different objects as being unequal.)
I suggest that you use a Captor to capture the Get object and add asserts to verify that the correct information is present. (I think this is a better way to write this sort of test anyway - it keeps all the assertions together, and leads to better error messages if you pass the wrong thing.)

Related

How to iterate a List of Model in java and update the value of some of model element in list

I have a array list of a Model class which has multiple String type variables.
This Array list values is populated from JDBC template result set.
Now I want to iterate this Array List and update some of these model element based upon some conditions.
My Model Class:
import lombok.Getter;
import lombok.Setter;
#Getter
#Setter
public class WADataModel {
public String STATUS;
public String AUTO_DATE;
public String RECORD_TYPE;
public String VENDOR_NAME;
public String CREATED_DATE;
public String ACTION_CODE;
public String CITY;
public String GROUP_NUMBER;
public String GROUP_POLICY_NUMBER;
public String SUBGROUP_NUMBER;
public String SUBGROUP_POLICY_NUMBER;
public String SYSTEM;
public String PLAN_NUMBER;
}
My DAO Class:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
#Component
public class PlanCrosswalks {
#Autowired
#Qualifier("nemisNamedJdbcTemplate")
private NamedParameterJdbcTemplate nemisJdbcTemplate;
#Autowired
private FetchDatafFromProp fetchDatafFromProp;
#Value("${query.state}")
private String queryState;
public List<WADataModel> doWACrosswalk(List<WADataModel> claimDataList) throws ApplicationExceptions{
RowMapper<WACrosswalkModel> rowMapper = new BeanPropertyRowMapper<>(WACrosswalkModel.class);
List<WACrosswalkModel> statusResult = new ArrayList<>();
Map<String,String> crosswalkQueryMap = new HashMap<>();
Map<String,String> paramMap = new HashMap<>();
crosswalkQueryMap = fetchDatafFromProp.getDataForGeneration();
statusResult = nemisJdbcTemplate.query(crosswalkQueryMap.get(queryState+ Constants.UNDERSCORE + Constants.FETCH_SUB_GROUP_POLICY),paramMap,rowMapper);
for(WADataModel model : claimDataList)
//Here I want to update ClaimDataList elements like SUBGROUP_POLICY_NUMBER,GROUP_POLICY_NUMBER based upon some conditions by iterating whole List.
return claimDataList;
}
}
I want to iterate "claimDataList" and check whether plan_number is null and update subGroupPolicyNumber accordingly based upon the value of plan_number.
I can iterate List of model but don't know how to update the values in List of model.
Please help me to update the values in "claimDataList"
Write a method to update one model.
Then you can iterate over the list of models, filter them and call this method for the resuming models.
I would prefer a stream:
claimDataList.stream()
.filter(model -> model.PLAN_NUMBER == null)
.forEach(this::planNumberNull);
private void planNumberNull(WADataModel model) {
model.SUBGROUP_POLICY_NUMBER = ...
}
for(WADataModel model : claimDataList){
if(model.PLAN_NUMBER==null){
model.SUBGROUP_POLICY_NUMBER = <>
}
}
If I have understood, you want to check that the value 'PLAN_NUMBER' is not null, and then fill the variable 'SUBGRUOUP_POLICY_NUMBER'.
You can do this with lambdas (since j8), which is optimal.
claimDataList.stream()
.filter(x -> x.getPLAN_NUMBER() != null)
.forEach(y -> y.setSUBGROUP_POLICY_NUMBER(y.getPLAN_NUMBER()));

XIRR implementation in Java

I tried using https://github.com/RayDeCampo/java-xirr but in some cases it's throwing the exception. If anyone has already solve the issue will be super helpful.
Not working example:
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import org.decampo.xirr.NewtonRaphson;
import org.decampo.xirr.Transaction;
import org.decampo.xirr.Xirr;
public class XIRR {
private static List<Transaction> txns = new ArrayList<>();
public static void main(String[] args) {
//txns.add(new Transaction(-100.0, "2022-05-29"));
//txns.add(new Transaction(-100.0, "2022-05-29"));
txns.add(new Transaction(-300.0, "2022-05-29"));
txns.add(new Transaction(295.47, "2022-05-31"));
double xirr = Xirr.builder()
.withTransactions(txns)
.withNewtonRaphsonBuilder(NewtonRaphson.builder().withIterations(10000).withTolerance(0.000001))
.withGuess(0.1)
.xirr()
*100;
System.out.println("xirr = " + xirr);
}
}
It is throwing an exception like
Exception in thread "main" org.decampo.xirr.OverflowException: Candidate overflow: {guess=0.1, iteration=140, candidate=-Infinity, value=-14359.837609828492, derivative=-4.844899455942689E-307}
at org.decampo.xirr.NewtonRaphson$Calculation.setCandidate(NewtonRaphson.java:166)
at org.decampo.xirr.NewtonRaphson$Calculation.solve(NewtonRaphson.java:213)
at org.decampo.xirr.NewtonRaphson.inverse(NewtonRaphson.java:89)
at org.decampo.xirr.NewtonRaphson.findRoot(NewtonRaphson.java:70)
at org.decampo.xirr.NewtonRaphson$Builder.findRoot(NewtonRaphson.java:136)
at org.decampo.xirr.Xirr.xirr(Xirr.java:155)
at org.decampo.xirr.Xirr$Builder.xirr(Xirr.java:262)
at com.app.experiments.XIRR.main(XIRR.java:27)
From excel, correct XIRR is -0.937760641

Mocking DynamoDB mapper query using Mockito

I am trying to mock a very simple line of code that is used to query the DynamoDB using Java. Here is some sample code for the query -
List<Pojo> result;
try {
if (filters == null) {
this.queryExpression = new DynamoDBQueryExpression<Pojo>()
.withKeyConditionExpression(partitionKeyCondition)
.withExpressionAttributeValues(this.eav);
} else {
setFilterQueryExpression(filters);
}
result = this.dynamoDBMapper.query(Pojo.class, queryExpression);
} catch (final Exception e) {
throw new InternalServerException("Something went wrong with the database query: ", e);
}
The above piece of code works and I am able to retrieve a List of rows that automatically get deserialized into the Pojo.
I am now trying to Mock the this.dynamoDBMapper.query call as follows -
#Mock
private DynamoDBMapper mapper;
List<Pojo> result = new ArrayList<>();
when(mapper.query(Pojo.class,Mockito.any(DynamoDBQueryExpression.class)).thenReturn(result);
I am unable to do that with error -
Cannot resolve method 'thenReturn(java.util.List<com.amazon.xxx.xxx.Pojo>)'
I also tried another way -
doReturn(result).when(mapper).query(Pojo.class, Mockito.any(DynamoDBQueryExpression.class));
That seems to compile but the test fails with error -
org.mockito.exceptions.misusing.WrongTypeOfReturnValue
I have looked at other sample where the expected output of the query is of type PaginatedQueryList , I have tried changing to that as well. But I am still not sure why the above throws an error.
Do you also get the error when you use ArgumentMatchers?
Mockito.when(mapper.query(ArgumentMatchers.any(Pojo.class),ArgumentMatchers.any(DynamoDBQueryExpression.class)).thenReturn(result));
Do you also get the error if you expand the ArgumentMatchers (temporarily)?
Mockito.when(mapper.query(ArgumentMatchers.any(),ArgumentMatchers.any()).thenReturn(result));
As it turns out, you are missing a parenthesis before .thenReturn in order to complete the when part. Once you add it and switch from return type List to PaginatedQueryList, it should compile. Also note that any is a matcher. Once you specifiy a matcher, all arguments need to be matchers, therefore use eq etc. for your Pojo type. Otherwise, Mockito will show a InvalidUseOfMatchersException during runtime. Here is a simplified example that works for me:
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression;
import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedQueryList;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MockTest {
#Test
void test() {
DynamoDBMapper mapperMock = mock(DynamoDBMapper.class);
PaginatedQueryList<String> expected = mock(PaginatedQueryList.class);
// Note that when needs to be completed before thenReturn can be called.
when(mapperMock.query(eq(String.class), Mockito.any(DynamoDBQueryExpression.class))).thenReturn(expected);
QueryService queryService = new QueryService(mapperMock);
PaginatedQueryList<String> actual = queryService.query();
assertEquals(expected, actual);
}
public class QueryService {
private final DynamoDBMapper mapper;
public QueryService(DynamoDBMapper mapper) {
this.mapper = mapper;
}
public PaginatedQueryList<String> query() {
DynamoDBQueryExpression<String> queryExpression = new DynamoDBQueryExpression<>();
return mapper.query(String.class, queryExpression);
}
}
}

How to validate #Xml.propOrder annotation values?

My team has been running into a recurring problem while serializing objects to XML: the class properties get updated, but the #Xml.propOrder annotation values do not (people forget), which causes the following error:
Property baz appears in #XmlType.propOrder, but no such property exists.
How can I automate a unit test to check all classes that declare #Xml.propOrder for undeclared fields or typos in the annotation value?
E.g:
#XmlRootElement
#XmlType(name = "FooBar", propOrder = { "bar", "baz", "foo" })
public class FooBar {
private String foo;
private int bar;
// getters and setters here...
}
IntelliJ sometimes can pick up the error during linting, but some team members use Eclipse, so code gets comitted, maven does not spew any warnings, and wrong code goes to test/QA. Also, our team cannot also change the build script, it's controlled and standardized company-wide.
I cobbled together a test that uses Guava to load information about all classes under a package name, load them, check if they have the #XmlType annotation, and if so, compares the values of the propOrder element with the class properties obtained through reflection.
I'm not totally happy with it, I wanted to use the same mechanism that Java uses to validate the annotations. But hey, it works.
package com.mycompany.datamodel;
import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ClassInfo;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import javax.xml.bind.annotation.XmlType;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import static org.junit.Assert.assertTrue;
#RunWith(Parameterized.class)
public class PropOrderTest {
#Parameter
public Class clazz;
#Parameters(name = "Test #XmlType.propOrder: {0}")
public static Collection<Class> data() throws IOException {
ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
String packageName = PropOrderTest.class.getPackage().getName();
Set<ClassInfo> allClasses = classPath.getTopLevelClassesRecursive(packageName);
List<Class> annotatedClasses = new ArrayList<Class>();
for (ClassInfo info : allClasses) {
Class clazz = info.load();
if (clazz.isAnnotationPresent(XmlType.class)) {
annotatedClasses.add(clazz);
}
}
return annotatedClasses;
}
#Test
public void testPropOder() throws IOException {
XmlType xmlType = (XmlType) clazz.getAnnotation(XmlType.class);
Set<String> propOrder = new HashSet<String>(Arrays.asList(xmlType.propOrder()));
// remove empty string returned when propOrder is not declared
propOrder.remove("");
List<String> fieldNames = getFieldNames();
propOrder.removeAll(fieldNames);
assertTrue(formatMessage(propOrder), propOrder.isEmpty());
}
private List<String> getFieldNames() {
Field[] fields = clazz.getDeclaredFields();
List<String> names = new ArrayList<String>(fields.length);
for (Field field : fields) {
names.add(field.getName());
}
return names;
}
private String formatMessage(Collection<String> propOrder) {
String message = null;
String props = "'" + StringUtils.join(propOrder.toArray(), "', '") + "'";
if (propOrder.size() > 1) {
message = "Properties %s appear in #XmlType.propOrder, but no such properties exist in class %s (%s.java:1).";
} else {
message = "Property %s appears in #XmlType.propOrder, but no such property exists in class %s (%s.java:1).";
}
return String.format(message, props, clazz.getName(), clazz.getSimpleName());
}
}

Deep inside jackson - how can I get the property name from a getter

I am digging on Jackson 2 and I want to know where and how the getter-method name gets converted into a property name.
I have tried:
PropertyName foo = new PropertyName("getKarli");
System.out.println(foo.getSimpleName());
I and I have found BeanProperty.Std() but this one have a lot of wired constructors. The api is bigger then expected :-) Is there a Jackson class and method where I can just pass the method and get back the correct property text used in the json?
EDIT:
I have also tried this one but that gives me a NullPointer
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyName;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class Test {
public String getKarli() {
return null;
}
public static void main(String[] a) throws Exception {
node.remove("geheim");
System.out.println(node.toString());
Annotated aa = new AnnotatedMethod(Test.class.getMethod("getKarli"), null, null);
System.out.println(
new ObjectMapper().getSerializationConfig().getAnnotationIntrospector().findNameForSerialization(aa)
);
// new BeanProperty.Std()
}
}
Found it.
String name = BeanUtil.okNameForRegularGetter(p, p.getName(), true);
if(name == null) name = BeanUtil.okNameForIsGetter(p, p.getName(), true);

Categories