Mocking an autowired object of base abstract classCan an abstract class have a constructor?Interface vs Abstract Class (general OO)Creating an abstract class in Objective-CWhat is the difference between an interface and abstract class?How to make mock to void methods with MockitoWhat is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?Why is my Spring @Autowired field null?Mocking SessionContex using mockito causes a ClassNotFoundExceptionMocked restTemplate.postForObject is not being used in execution of testJUnit - Private method causing test to fail
Are wands in any sort of book going to be too much like Harry Potter?
Why did Ham the Chimp push levers?
Trying to understand a summation
Capturing the entire webpage with WebExecute's CaptureImage
Opposite party turned away from voting when ballot is all opposing party
Where do 5 or more U.S. counties meet in a single point?
How to avoid making self and former employee look bad when reporting on fixing former employee's work?
Employee is self-centered and affects the team negatively
Can I bring back Planetary Romance as a genre?
Was Mohammed the most popular first name for boys born in Berlin in 2018?
My perfect evil overlord plan... or is it?
The unknown and unexplained in science fiction
Does this website provide consistent translation into Wookiee?
What's an appropriate age to involve kids in life changing decisions?
Gift for mentor after his thesis defense?
Why does this pattern in powers happen?
Linear Independence for Vectors of Cosine Values
How is it believable that Euron could so easily pull off this ambush?
Is there a need for better software for writers?
Visual Studio Code download existing code
When was it publicly revealed that a KH-11 spy satellite took pictures of the first Shuttle flight?
Is it a good idea to copy a trader when investing?
Why is it wrong to *implement* myself a known, published, widely believed to be secure crypto algorithm?
Magical Modulo Squares
Mocking an autowired object of base abstract class
Can an abstract class have a constructor?Interface vs Abstract Class (general OO)Creating an abstract class in Objective-CWhat is the difference between an interface and abstract class?How to make mock to void methods with MockitoWhat is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?Why is my Spring @Autowired field null?Mocking SessionContex using mockito causes a ClassNotFoundExceptionMocked restTemplate.postForObject is not being used in execution of testJUnit - Private method causing test to fail
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I'm writing the Junit test case for a class which is extended by an abstract class. This base abstract class has an autowired object of a different class which is being used in the class I'm testing.
I'm trying to mock in the subclass, but the mocked object is throwing a NullPointerException.
Example:
// class I am testing
public class GetTransactionsForProcessorGroupActivity extends GetTransactionsBaseActivity
private static final Logger log = LogManager.getLogger(GetTransactionsForProcessorGroupActivity.class);
public GetTransactionsForProcessorGroupActivity(ARHFactory arhFactory, MetricsFactory metricsFactory)
super(arhFactory, metricsFactory);
@Override
protected List<OverseasTransaction> getOverseasTransactions(Document herdDocument)
throws IllegalDateFormatException, ProcessorConfigurationException, DocumentException
final String paymentProcessorGroup = HerdDocumentUtils.getPaymentProcessor(herdDocument);
final Date runDate = HerdDocumentUtils.getRunDate(herdDocument);
final List<String> paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup);
List<OverseasTransaction> overseasTransactionList = new ArrayList<OverseasTransaction>();
List<ProcessorTransactionWindow> processingWindows = new ArrayList<ProcessorTransactionWindow>();
for (final String processor : paymentProcessorList)
ProcessorTransactionWindow transactionWindow = ProcessorCalendarUtils.getProcessorTransactionWindow(processor, runDate);
processingWindows.add(transactionWindow);
final Date processingFromDate = transactionWindow.getFromDate();
final Date processingToDate = transactionWindow.getToDate();
//NullpointerException on this line, as OverseasTransactionStore mock object returns null.
final List<OverseasTransaction> transactions = overseasTransactionsStore
.queryOverseasTransactionsOnPPTimelineandDates(processor, processingFromDate, processingToDate);
overseasTransactionList.addAll(transactions);
HerdDocumentUtils.putProcessingWindowDetails(herdDocument, processingWindows);
return overseasTransactionList;
// Base class
public abstract class GetTransactionsBaseActivity extends CoralHerdActivity implements ActionRequestHandler
private static final Logger log = LogManager.getLogger(GetTransactionsBaseActivity.class);
@SuppressWarnings("unchecked")
private static final Map<String, String> S3_CONFIGURATION = AppConfig.findMap(Constants.S3_CONFIGURATION_KEY);
private static final String S3_BUCKET = S3_CONFIGURATION.get(Constants.BUCKET_NAME);
private static final class Status
private static final String PROCESSOR_DETAILS_NOT_FOUND = "NoPaymentProcessorDetailsPresent";
private static final String TRANSACTIONS_OBTAINED = "TransactionsObtained";
private static final String NO_TRANSACTIONS_TO_BE_CONSIDERED = "NoTransactionsToBeConsidered";
private static final String NEGATIVE_OR_ZERO_AMOUNT = "NegativeOrZeroAmount";
protected final ARHFactory arhFactory;
protected final MetricsFactory metricsFactory;
@Autowired
OverseasTransactionsStore overseasTransactionsStore;
@Autowired
S3ClientProvider s3ClientProvider;
protected abstract List<OverseasTransaction> getOverseasTransactions(Document herdDocument)
throws IllegalDateFormatException, ProcessorConfigurationException, DocumentException;
@Override
public ActionResponse postActionRequest(final ActionRequest request) throws Exception
TimedARH timedARH = (TimedARH) arhFactory.createARH();
timedARH.setHandler(this);
return timedARH.handle(request);
public ActionResponse handle(final ActionRequest request) throws Exception
final Document herdDocument = HerdDocumentUtils.getFundFlowDocument(request);
final Metrics metrics = MetricsLogger.getMetrics(metricsFactory);
final String paymentProcessor = HerdDocumentUtils.getPaymentProcessor(herdDocument);
try
final List<OverseasTransaction> overseasTransactionList;
MetricsLogger.logFundFlowExecution(metrics, paymentProcessor);
try
overseasTransactionList = getOverseasTransactions(herdDocument);
catch (ProcessorConfigurationException e)
return new ActionComplete(Status.PROCESSOR_DETAILS_NOT_FOUND, herdDocument);
if (CollectionUtils.isEmpty(overseasTransactionList))
MetricsLogger.logTransactionMetrics(metrics, paymentProcessor, 0, BigDecimal.ZERO);
return new ActionComplete(Status.NO_TRANSACTIONS_TO_BE_CONSIDERED, herdDocument);
final String s3ObjectKey = getS3ObjectKey(request, paymentProcessor);
storeTransactionsInS3(overseasTransactionList, S3_BUCKET, s3ObjectKey);
final int itemCount = overseasTransactionList.size();
BigDecimal totalAmount = BigDecimal.ZERO;
for (OverseasTransaction overseasTransaction : overseasTransactionList)
if (StringUtils.equalsIgnoreCase(overseasTransaction.getType(), Constants.TRANSACTION_TYPE_CHARGE))
totalAmount = totalAmount.add(overseasTransaction.getOverseasAmount());
else if (StringUtils.equalsIgnoreCase(overseasTransaction.getType(), Constants.TRANSACTION_TYPE_REFUND))
totalAmount = totalAmount.subtract(overseasTransaction.getOverseasAmount());
MetricsLogger.logTransactionMetrics(metrics, paymentProcessor, itemCount, totalAmount);
HerdDocumentUtils.putS3Location(herdDocument, S3_BUCKET, s3ObjectKey);
HerdDocumentUtils.putTotalAmount(herdDocument, totalAmount);
HerdDocumentUtils.putTransactionItemCount(herdDocument, itemCount);
HerdDocumentUtils.putPaymentProcessor(herdDocument, paymentProcessor);
if (totalAmount.compareTo(BigDecimal.ZERO) <= 0)
log.info("Total amount to disburse is zero or negative. ", totalAmount);
return new ActionComplete(Status.NEGATIVE_OR_ZERO_AMOUNT, herdDocument);
return new ActionComplete(Status.TRANSACTIONS_OBTAINED, herdDocument);
finally
MetricsLogger.closeMetrics(metrics);
// Test class
@RunWith(PowerMockRunner.class)
@PowerMockIgnore( "javax.management.*" )
@PrepareForTest( HerdDocumentUtils.class, ProcessorGroupLookup.class )
public class GetTransactionsForProcessorGroupActivityTest extends AppConfigInitializedTestBase
private static HerdInput herdInput;
private static HerdOutput herdOutput;
private static final String paymentProcessorGroup = "BillDesk";
private static final String paymentProcessorGroupNotFound = "IndiaPaymentGateway";
@Mock
ActionRequest request;
@Mock
WorkItemIdentifier workItemId;
@Mock
private CoralHerdActivity coralHerdActivity;
@Mock
Metrics metrics;
@Mock
Map<String, String> S3_CONFIGURATION_MAP;
@Mock
MetricsFactory metricsFactory;
@Mock
ARHFactory arhFactory;
@Mock
Document herdDocument;
@Mock
OverseasTransactionsStore overseasTransactionsStore;
@Mock
S3ClientProvider s3ClientProvider;
// @InjectMocks
// GetTransactionsForProcessorGroupActivity getTransactionsBaseActivityTest;
// new GetTransactionsForProcessorGroupActivity(arhFactory, metricsFactory);
@Before
public void setup()
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(HerdDocumentUtils.class);
// PowerMockito.mockStatic(ProcessorGroupLookup.class);
// GetTransactionsBaseActivity getTransactionsBaseActivity = new GetTransactionsBaseActivity(overseasTransactionsStore);
@Test
public void testEnact()
GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity = Mockito
.mock(GetTransactionsForProcessorGroupActivity.class, Mockito.CALLS_REAL_METHODS);
Mockito.when(coralHerdActivity.enact(herdInput)).thenReturn(herdOutput);
final HerdOutput actualHerdOutput = getTransactionsForProcessorGroupActivity.enact(herdInput);
Assert.assertNotNull(actualHerdOutput);
@Test
public void testgetpaymentProcessorList() throws Exception
Date date = new Date();
List<String> paymentProcessorList;
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument)).thenReturn(paymentProcessorGroup);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup);
assertNotNull(paymentProcessorList);
@Test(expected = ProcessorConfigurationException.class)
public void testpaymentProcessorListNotFound()
Date date = new Date();
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument))
.thenReturn(paymentProcessorGroupNotFound);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
List<String> paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroupNotFound);
assertNotNull(paymentProcessorList);
@Test
public void canGetOverseasTransactiontest() throws Exception
GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity = Mockito
.mock(GetTransactionsForProcessorGroupActivity.class);
// OverseasTransactionsStore overseasTransactionsStore =
// Mockito.mock(OverseasTransactionsStoreImpl.class);
Date date = new Date();
MockitoAnnotations.initMocks(this);
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument)).thenReturn(paymentProcessorGroup);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
// List<String> paymentProcessorList = new ArrayList<>();
// paymentProcessorList.add("BillDesk");
// PowerMockito.when(ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup))
// .thenReturn(paymentProcessorList);
String fromDate = "Sat Mar 16 23:59:59 IST 2019";
String toDate = "Sat Mar 16 23:59:59 IST 2019";
DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
List<OverseasTransaction> overseasTransactionList1 = createMockOverseasTransaction();
Mockito.doReturn(overseasTransactionList1).when(overseasTransactionsStore)
.queryOverseasTransactionsOnPPTimelineandDates(Mockito.isA(String.class), Mockito.isA(Date.class),
Mockito.isA(Date.class));
Mockito.when(getTransactionsForProcessorGroupActivity.getOverseasTransactions(herdDocument))
.thenCallRealMethod();
List<OverseasTransaction> overseasTransactionList = getTransactionsForProcessorGroupActivity
.getOverseasTransactions(herdDocument);
assertNotNull(overseasTransactionList);
// assertEquals(overseasTransactionList.getPaymentProcessorID(), actual);
private List<OverseasTransaction> createMockOverseasTransaction()
Date date = new Date();
BigDecimal num = new BigDecimal(100001);
List<OverseasTransaction> overseasTransactionList = new ArrayList<OverseasTransaction>();
OverseasTransaction overseasTransaction = new OverseasTransaction();
overseasTransaction.setPurchaseID("purchaseID");
overseasTransaction.setSignatureID("signatureID");
overseasTransaction.setPaymentProcessorTransactionID("paymentProcessorTransactionID");
overseasTransaction.setType("Charge");
overseasTransaction.setSubType("subType");
overseasTransaction.setTransactionTimestamp(date);
overseasTransaction.setPaymentMethod("paymentMethod");
overseasTransaction.setTotalAmount(num);
overseasTransaction.setOverseasAmount(num);
overseasTransaction.setCurrency("currency");
overseasTransaction.setMarketplaceID("marketplaceID");
overseasTransaction.setOrderMetadata("orderMetadata");
overseasTransaction.setDisbursementID("disbursementID");
overseasTransaction.setReconState(1);
overseasTransaction.setPaymentProcessorID("BillDesk");
overseasTransaction.setRemittanceFileStatus("remittanceFileStatus");
overseasTransaction.setCrowID("crowID");
overseasTransaction.setSource("source");
overseasTransactionList.add(overseasTransaction);
return overseasTransactionList;
In my test file when I mock OverseasTransaction object, it gives me a NullPointerException. Do you have any suggestions about how we can mock this? All the above commented lines in my test indicates the things I tried but they still seem to throw the same error.
StackTrace of error: while executing canGetOverseasTransactiontest
N/A
java.lang.NullPointerException
at com.ingsfundflowservice.activity.GetTransactionsForProcessorGroupActivity.getOverseasTransactions(GetTransactionsForProcessorGroupActivity.java:71)
at com.ingsfundflowservice.activity.GetTransactionsForProcessorGroupActivityTest.canGetOverseasTransactiontest(GetTransactionsForProcessorGroupActivityTest.java:172)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
spring junit mockito abstract-class autowired
add a comment |
I'm writing the Junit test case for a class which is extended by an abstract class. This base abstract class has an autowired object of a different class which is being used in the class I'm testing.
I'm trying to mock in the subclass, but the mocked object is throwing a NullPointerException.
Example:
// class I am testing
public class GetTransactionsForProcessorGroupActivity extends GetTransactionsBaseActivity
private static final Logger log = LogManager.getLogger(GetTransactionsForProcessorGroupActivity.class);
public GetTransactionsForProcessorGroupActivity(ARHFactory arhFactory, MetricsFactory metricsFactory)
super(arhFactory, metricsFactory);
@Override
protected List<OverseasTransaction> getOverseasTransactions(Document herdDocument)
throws IllegalDateFormatException, ProcessorConfigurationException, DocumentException
final String paymentProcessorGroup = HerdDocumentUtils.getPaymentProcessor(herdDocument);
final Date runDate = HerdDocumentUtils.getRunDate(herdDocument);
final List<String> paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup);
List<OverseasTransaction> overseasTransactionList = new ArrayList<OverseasTransaction>();
List<ProcessorTransactionWindow> processingWindows = new ArrayList<ProcessorTransactionWindow>();
for (final String processor : paymentProcessorList)
ProcessorTransactionWindow transactionWindow = ProcessorCalendarUtils.getProcessorTransactionWindow(processor, runDate);
processingWindows.add(transactionWindow);
final Date processingFromDate = transactionWindow.getFromDate();
final Date processingToDate = transactionWindow.getToDate();
//NullpointerException on this line, as OverseasTransactionStore mock object returns null.
final List<OverseasTransaction> transactions = overseasTransactionsStore
.queryOverseasTransactionsOnPPTimelineandDates(processor, processingFromDate, processingToDate);
overseasTransactionList.addAll(transactions);
HerdDocumentUtils.putProcessingWindowDetails(herdDocument, processingWindows);
return overseasTransactionList;
// Base class
public abstract class GetTransactionsBaseActivity extends CoralHerdActivity implements ActionRequestHandler
private static final Logger log = LogManager.getLogger(GetTransactionsBaseActivity.class);
@SuppressWarnings("unchecked")
private static final Map<String, String> S3_CONFIGURATION = AppConfig.findMap(Constants.S3_CONFIGURATION_KEY);
private static final String S3_BUCKET = S3_CONFIGURATION.get(Constants.BUCKET_NAME);
private static final class Status
private static final String PROCESSOR_DETAILS_NOT_FOUND = "NoPaymentProcessorDetailsPresent";
private static final String TRANSACTIONS_OBTAINED = "TransactionsObtained";
private static final String NO_TRANSACTIONS_TO_BE_CONSIDERED = "NoTransactionsToBeConsidered";
private static final String NEGATIVE_OR_ZERO_AMOUNT = "NegativeOrZeroAmount";
protected final ARHFactory arhFactory;
protected final MetricsFactory metricsFactory;
@Autowired
OverseasTransactionsStore overseasTransactionsStore;
@Autowired
S3ClientProvider s3ClientProvider;
protected abstract List<OverseasTransaction> getOverseasTransactions(Document herdDocument)
throws IllegalDateFormatException, ProcessorConfigurationException, DocumentException;
@Override
public ActionResponse postActionRequest(final ActionRequest request) throws Exception
TimedARH timedARH = (TimedARH) arhFactory.createARH();
timedARH.setHandler(this);
return timedARH.handle(request);
public ActionResponse handle(final ActionRequest request) throws Exception
final Document herdDocument = HerdDocumentUtils.getFundFlowDocument(request);
final Metrics metrics = MetricsLogger.getMetrics(metricsFactory);
final String paymentProcessor = HerdDocumentUtils.getPaymentProcessor(herdDocument);
try
final List<OverseasTransaction> overseasTransactionList;
MetricsLogger.logFundFlowExecution(metrics, paymentProcessor);
try
overseasTransactionList = getOverseasTransactions(herdDocument);
catch (ProcessorConfigurationException e)
return new ActionComplete(Status.PROCESSOR_DETAILS_NOT_FOUND, herdDocument);
if (CollectionUtils.isEmpty(overseasTransactionList))
MetricsLogger.logTransactionMetrics(metrics, paymentProcessor, 0, BigDecimal.ZERO);
return new ActionComplete(Status.NO_TRANSACTIONS_TO_BE_CONSIDERED, herdDocument);
final String s3ObjectKey = getS3ObjectKey(request, paymentProcessor);
storeTransactionsInS3(overseasTransactionList, S3_BUCKET, s3ObjectKey);
final int itemCount = overseasTransactionList.size();
BigDecimal totalAmount = BigDecimal.ZERO;
for (OverseasTransaction overseasTransaction : overseasTransactionList)
if (StringUtils.equalsIgnoreCase(overseasTransaction.getType(), Constants.TRANSACTION_TYPE_CHARGE))
totalAmount = totalAmount.add(overseasTransaction.getOverseasAmount());
else if (StringUtils.equalsIgnoreCase(overseasTransaction.getType(), Constants.TRANSACTION_TYPE_REFUND))
totalAmount = totalAmount.subtract(overseasTransaction.getOverseasAmount());
MetricsLogger.logTransactionMetrics(metrics, paymentProcessor, itemCount, totalAmount);
HerdDocumentUtils.putS3Location(herdDocument, S3_BUCKET, s3ObjectKey);
HerdDocumentUtils.putTotalAmount(herdDocument, totalAmount);
HerdDocumentUtils.putTransactionItemCount(herdDocument, itemCount);
HerdDocumentUtils.putPaymentProcessor(herdDocument, paymentProcessor);
if (totalAmount.compareTo(BigDecimal.ZERO) <= 0)
log.info("Total amount to disburse is zero or negative. ", totalAmount);
return new ActionComplete(Status.NEGATIVE_OR_ZERO_AMOUNT, herdDocument);
return new ActionComplete(Status.TRANSACTIONS_OBTAINED, herdDocument);
finally
MetricsLogger.closeMetrics(metrics);
// Test class
@RunWith(PowerMockRunner.class)
@PowerMockIgnore( "javax.management.*" )
@PrepareForTest( HerdDocumentUtils.class, ProcessorGroupLookup.class )
public class GetTransactionsForProcessorGroupActivityTest extends AppConfigInitializedTestBase
private static HerdInput herdInput;
private static HerdOutput herdOutput;
private static final String paymentProcessorGroup = "BillDesk";
private static final String paymentProcessorGroupNotFound = "IndiaPaymentGateway";
@Mock
ActionRequest request;
@Mock
WorkItemIdentifier workItemId;
@Mock
private CoralHerdActivity coralHerdActivity;
@Mock
Metrics metrics;
@Mock
Map<String, String> S3_CONFIGURATION_MAP;
@Mock
MetricsFactory metricsFactory;
@Mock
ARHFactory arhFactory;
@Mock
Document herdDocument;
@Mock
OverseasTransactionsStore overseasTransactionsStore;
@Mock
S3ClientProvider s3ClientProvider;
// @InjectMocks
// GetTransactionsForProcessorGroupActivity getTransactionsBaseActivityTest;
// new GetTransactionsForProcessorGroupActivity(arhFactory, metricsFactory);
@Before
public void setup()
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(HerdDocumentUtils.class);
// PowerMockito.mockStatic(ProcessorGroupLookup.class);
// GetTransactionsBaseActivity getTransactionsBaseActivity = new GetTransactionsBaseActivity(overseasTransactionsStore);
@Test
public void testEnact()
GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity = Mockito
.mock(GetTransactionsForProcessorGroupActivity.class, Mockito.CALLS_REAL_METHODS);
Mockito.when(coralHerdActivity.enact(herdInput)).thenReturn(herdOutput);
final HerdOutput actualHerdOutput = getTransactionsForProcessorGroupActivity.enact(herdInput);
Assert.assertNotNull(actualHerdOutput);
@Test
public void testgetpaymentProcessorList() throws Exception
Date date = new Date();
List<String> paymentProcessorList;
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument)).thenReturn(paymentProcessorGroup);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup);
assertNotNull(paymentProcessorList);
@Test(expected = ProcessorConfigurationException.class)
public void testpaymentProcessorListNotFound()
Date date = new Date();
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument))
.thenReturn(paymentProcessorGroupNotFound);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
List<String> paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroupNotFound);
assertNotNull(paymentProcessorList);
@Test
public void canGetOverseasTransactiontest() throws Exception
GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity = Mockito
.mock(GetTransactionsForProcessorGroupActivity.class);
// OverseasTransactionsStore overseasTransactionsStore =
// Mockito.mock(OverseasTransactionsStoreImpl.class);
Date date = new Date();
MockitoAnnotations.initMocks(this);
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument)).thenReturn(paymentProcessorGroup);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
// List<String> paymentProcessorList = new ArrayList<>();
// paymentProcessorList.add("BillDesk");
// PowerMockito.when(ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup))
// .thenReturn(paymentProcessorList);
String fromDate = "Sat Mar 16 23:59:59 IST 2019";
String toDate = "Sat Mar 16 23:59:59 IST 2019";
DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
List<OverseasTransaction> overseasTransactionList1 = createMockOverseasTransaction();
Mockito.doReturn(overseasTransactionList1).when(overseasTransactionsStore)
.queryOverseasTransactionsOnPPTimelineandDates(Mockito.isA(String.class), Mockito.isA(Date.class),
Mockito.isA(Date.class));
Mockito.when(getTransactionsForProcessorGroupActivity.getOverseasTransactions(herdDocument))
.thenCallRealMethod();
List<OverseasTransaction> overseasTransactionList = getTransactionsForProcessorGroupActivity
.getOverseasTransactions(herdDocument);
assertNotNull(overseasTransactionList);
// assertEquals(overseasTransactionList.getPaymentProcessorID(), actual);
private List<OverseasTransaction> createMockOverseasTransaction()
Date date = new Date();
BigDecimal num = new BigDecimal(100001);
List<OverseasTransaction> overseasTransactionList = new ArrayList<OverseasTransaction>();
OverseasTransaction overseasTransaction = new OverseasTransaction();
overseasTransaction.setPurchaseID("purchaseID");
overseasTransaction.setSignatureID("signatureID");
overseasTransaction.setPaymentProcessorTransactionID("paymentProcessorTransactionID");
overseasTransaction.setType("Charge");
overseasTransaction.setSubType("subType");
overseasTransaction.setTransactionTimestamp(date);
overseasTransaction.setPaymentMethod("paymentMethod");
overseasTransaction.setTotalAmount(num);
overseasTransaction.setOverseasAmount(num);
overseasTransaction.setCurrency("currency");
overseasTransaction.setMarketplaceID("marketplaceID");
overseasTransaction.setOrderMetadata("orderMetadata");
overseasTransaction.setDisbursementID("disbursementID");
overseasTransaction.setReconState(1);
overseasTransaction.setPaymentProcessorID("BillDesk");
overseasTransaction.setRemittanceFileStatus("remittanceFileStatus");
overseasTransaction.setCrowID("crowID");
overseasTransaction.setSource("source");
overseasTransactionList.add(overseasTransaction);
return overseasTransactionList;
In my test file when I mock OverseasTransaction object, it gives me a NullPointerException. Do you have any suggestions about how we can mock this? All the above commented lines in my test indicates the things I tried but they still seem to throw the same error.
StackTrace of error: while executing canGetOverseasTransactiontest
N/A
java.lang.NullPointerException
at com.ingsfundflowservice.activity.GetTransactionsForProcessorGroupActivity.getOverseasTransactions(GetTransactionsForProcessorGroupActivity.java:71)
at com.ingsfundflowservice.activity.GetTransactionsForProcessorGroupActivityTest.canGetOverseasTransactiontest(GetTransactionsForProcessorGroupActivityTest.java:172)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
spring junit mockito abstract-class autowired
My all imports and @prepareForTest annotations are in place. I have also initialized my Mocks in Before using Mockito.init(this).
– Shefali Chaudhary
Mar 22 at 16:02
First of all, removePowerMockito.Mock
, just dowhen(overseastransaction.somemethod()).thenReturn(something)
, this is how you define behavior. Second, how are you injecting the mock in your object under test?
– Morfic
Mar 22 at 16:14
add a comment |
I'm writing the Junit test case for a class which is extended by an abstract class. This base abstract class has an autowired object of a different class which is being used in the class I'm testing.
I'm trying to mock in the subclass, but the mocked object is throwing a NullPointerException.
Example:
// class I am testing
public class GetTransactionsForProcessorGroupActivity extends GetTransactionsBaseActivity
private static final Logger log = LogManager.getLogger(GetTransactionsForProcessorGroupActivity.class);
public GetTransactionsForProcessorGroupActivity(ARHFactory arhFactory, MetricsFactory metricsFactory)
super(arhFactory, metricsFactory);
@Override
protected List<OverseasTransaction> getOverseasTransactions(Document herdDocument)
throws IllegalDateFormatException, ProcessorConfigurationException, DocumentException
final String paymentProcessorGroup = HerdDocumentUtils.getPaymentProcessor(herdDocument);
final Date runDate = HerdDocumentUtils.getRunDate(herdDocument);
final List<String> paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup);
List<OverseasTransaction> overseasTransactionList = new ArrayList<OverseasTransaction>();
List<ProcessorTransactionWindow> processingWindows = new ArrayList<ProcessorTransactionWindow>();
for (final String processor : paymentProcessorList)
ProcessorTransactionWindow transactionWindow = ProcessorCalendarUtils.getProcessorTransactionWindow(processor, runDate);
processingWindows.add(transactionWindow);
final Date processingFromDate = transactionWindow.getFromDate();
final Date processingToDate = transactionWindow.getToDate();
//NullpointerException on this line, as OverseasTransactionStore mock object returns null.
final List<OverseasTransaction> transactions = overseasTransactionsStore
.queryOverseasTransactionsOnPPTimelineandDates(processor, processingFromDate, processingToDate);
overseasTransactionList.addAll(transactions);
HerdDocumentUtils.putProcessingWindowDetails(herdDocument, processingWindows);
return overseasTransactionList;
// Base class
public abstract class GetTransactionsBaseActivity extends CoralHerdActivity implements ActionRequestHandler
private static final Logger log = LogManager.getLogger(GetTransactionsBaseActivity.class);
@SuppressWarnings("unchecked")
private static final Map<String, String> S3_CONFIGURATION = AppConfig.findMap(Constants.S3_CONFIGURATION_KEY);
private static final String S3_BUCKET = S3_CONFIGURATION.get(Constants.BUCKET_NAME);
private static final class Status
private static final String PROCESSOR_DETAILS_NOT_FOUND = "NoPaymentProcessorDetailsPresent";
private static final String TRANSACTIONS_OBTAINED = "TransactionsObtained";
private static final String NO_TRANSACTIONS_TO_BE_CONSIDERED = "NoTransactionsToBeConsidered";
private static final String NEGATIVE_OR_ZERO_AMOUNT = "NegativeOrZeroAmount";
protected final ARHFactory arhFactory;
protected final MetricsFactory metricsFactory;
@Autowired
OverseasTransactionsStore overseasTransactionsStore;
@Autowired
S3ClientProvider s3ClientProvider;
protected abstract List<OverseasTransaction> getOverseasTransactions(Document herdDocument)
throws IllegalDateFormatException, ProcessorConfigurationException, DocumentException;
@Override
public ActionResponse postActionRequest(final ActionRequest request) throws Exception
TimedARH timedARH = (TimedARH) arhFactory.createARH();
timedARH.setHandler(this);
return timedARH.handle(request);
public ActionResponse handle(final ActionRequest request) throws Exception
final Document herdDocument = HerdDocumentUtils.getFundFlowDocument(request);
final Metrics metrics = MetricsLogger.getMetrics(metricsFactory);
final String paymentProcessor = HerdDocumentUtils.getPaymentProcessor(herdDocument);
try
final List<OverseasTransaction> overseasTransactionList;
MetricsLogger.logFundFlowExecution(metrics, paymentProcessor);
try
overseasTransactionList = getOverseasTransactions(herdDocument);
catch (ProcessorConfigurationException e)
return new ActionComplete(Status.PROCESSOR_DETAILS_NOT_FOUND, herdDocument);
if (CollectionUtils.isEmpty(overseasTransactionList))
MetricsLogger.logTransactionMetrics(metrics, paymentProcessor, 0, BigDecimal.ZERO);
return new ActionComplete(Status.NO_TRANSACTIONS_TO_BE_CONSIDERED, herdDocument);
final String s3ObjectKey = getS3ObjectKey(request, paymentProcessor);
storeTransactionsInS3(overseasTransactionList, S3_BUCKET, s3ObjectKey);
final int itemCount = overseasTransactionList.size();
BigDecimal totalAmount = BigDecimal.ZERO;
for (OverseasTransaction overseasTransaction : overseasTransactionList)
if (StringUtils.equalsIgnoreCase(overseasTransaction.getType(), Constants.TRANSACTION_TYPE_CHARGE))
totalAmount = totalAmount.add(overseasTransaction.getOverseasAmount());
else if (StringUtils.equalsIgnoreCase(overseasTransaction.getType(), Constants.TRANSACTION_TYPE_REFUND))
totalAmount = totalAmount.subtract(overseasTransaction.getOverseasAmount());
MetricsLogger.logTransactionMetrics(metrics, paymentProcessor, itemCount, totalAmount);
HerdDocumentUtils.putS3Location(herdDocument, S3_BUCKET, s3ObjectKey);
HerdDocumentUtils.putTotalAmount(herdDocument, totalAmount);
HerdDocumentUtils.putTransactionItemCount(herdDocument, itemCount);
HerdDocumentUtils.putPaymentProcessor(herdDocument, paymentProcessor);
if (totalAmount.compareTo(BigDecimal.ZERO) <= 0)
log.info("Total amount to disburse is zero or negative. ", totalAmount);
return new ActionComplete(Status.NEGATIVE_OR_ZERO_AMOUNT, herdDocument);
return new ActionComplete(Status.TRANSACTIONS_OBTAINED, herdDocument);
finally
MetricsLogger.closeMetrics(metrics);
// Test class
@RunWith(PowerMockRunner.class)
@PowerMockIgnore( "javax.management.*" )
@PrepareForTest( HerdDocumentUtils.class, ProcessorGroupLookup.class )
public class GetTransactionsForProcessorGroupActivityTest extends AppConfigInitializedTestBase
private static HerdInput herdInput;
private static HerdOutput herdOutput;
private static final String paymentProcessorGroup = "BillDesk";
private static final String paymentProcessorGroupNotFound = "IndiaPaymentGateway";
@Mock
ActionRequest request;
@Mock
WorkItemIdentifier workItemId;
@Mock
private CoralHerdActivity coralHerdActivity;
@Mock
Metrics metrics;
@Mock
Map<String, String> S3_CONFIGURATION_MAP;
@Mock
MetricsFactory metricsFactory;
@Mock
ARHFactory arhFactory;
@Mock
Document herdDocument;
@Mock
OverseasTransactionsStore overseasTransactionsStore;
@Mock
S3ClientProvider s3ClientProvider;
// @InjectMocks
// GetTransactionsForProcessorGroupActivity getTransactionsBaseActivityTest;
// new GetTransactionsForProcessorGroupActivity(arhFactory, metricsFactory);
@Before
public void setup()
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(HerdDocumentUtils.class);
// PowerMockito.mockStatic(ProcessorGroupLookup.class);
// GetTransactionsBaseActivity getTransactionsBaseActivity = new GetTransactionsBaseActivity(overseasTransactionsStore);
@Test
public void testEnact()
GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity = Mockito
.mock(GetTransactionsForProcessorGroupActivity.class, Mockito.CALLS_REAL_METHODS);
Mockito.when(coralHerdActivity.enact(herdInput)).thenReturn(herdOutput);
final HerdOutput actualHerdOutput = getTransactionsForProcessorGroupActivity.enact(herdInput);
Assert.assertNotNull(actualHerdOutput);
@Test
public void testgetpaymentProcessorList() throws Exception
Date date = new Date();
List<String> paymentProcessorList;
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument)).thenReturn(paymentProcessorGroup);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup);
assertNotNull(paymentProcessorList);
@Test(expected = ProcessorConfigurationException.class)
public void testpaymentProcessorListNotFound()
Date date = new Date();
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument))
.thenReturn(paymentProcessorGroupNotFound);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
List<String> paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroupNotFound);
assertNotNull(paymentProcessorList);
@Test
public void canGetOverseasTransactiontest() throws Exception
GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity = Mockito
.mock(GetTransactionsForProcessorGroupActivity.class);
// OverseasTransactionsStore overseasTransactionsStore =
// Mockito.mock(OverseasTransactionsStoreImpl.class);
Date date = new Date();
MockitoAnnotations.initMocks(this);
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument)).thenReturn(paymentProcessorGroup);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
// List<String> paymentProcessorList = new ArrayList<>();
// paymentProcessorList.add("BillDesk");
// PowerMockito.when(ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup))
// .thenReturn(paymentProcessorList);
String fromDate = "Sat Mar 16 23:59:59 IST 2019";
String toDate = "Sat Mar 16 23:59:59 IST 2019";
DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
List<OverseasTransaction> overseasTransactionList1 = createMockOverseasTransaction();
Mockito.doReturn(overseasTransactionList1).when(overseasTransactionsStore)
.queryOverseasTransactionsOnPPTimelineandDates(Mockito.isA(String.class), Mockito.isA(Date.class),
Mockito.isA(Date.class));
Mockito.when(getTransactionsForProcessorGroupActivity.getOverseasTransactions(herdDocument))
.thenCallRealMethod();
List<OverseasTransaction> overseasTransactionList = getTransactionsForProcessorGroupActivity
.getOverseasTransactions(herdDocument);
assertNotNull(overseasTransactionList);
// assertEquals(overseasTransactionList.getPaymentProcessorID(), actual);
private List<OverseasTransaction> createMockOverseasTransaction()
Date date = new Date();
BigDecimal num = new BigDecimal(100001);
List<OverseasTransaction> overseasTransactionList = new ArrayList<OverseasTransaction>();
OverseasTransaction overseasTransaction = new OverseasTransaction();
overseasTransaction.setPurchaseID("purchaseID");
overseasTransaction.setSignatureID("signatureID");
overseasTransaction.setPaymentProcessorTransactionID("paymentProcessorTransactionID");
overseasTransaction.setType("Charge");
overseasTransaction.setSubType("subType");
overseasTransaction.setTransactionTimestamp(date);
overseasTransaction.setPaymentMethod("paymentMethod");
overseasTransaction.setTotalAmount(num);
overseasTransaction.setOverseasAmount(num);
overseasTransaction.setCurrency("currency");
overseasTransaction.setMarketplaceID("marketplaceID");
overseasTransaction.setOrderMetadata("orderMetadata");
overseasTransaction.setDisbursementID("disbursementID");
overseasTransaction.setReconState(1);
overseasTransaction.setPaymentProcessorID("BillDesk");
overseasTransaction.setRemittanceFileStatus("remittanceFileStatus");
overseasTransaction.setCrowID("crowID");
overseasTransaction.setSource("source");
overseasTransactionList.add(overseasTransaction);
return overseasTransactionList;
In my test file when I mock OverseasTransaction object, it gives me a NullPointerException. Do you have any suggestions about how we can mock this? All the above commented lines in my test indicates the things I tried but they still seem to throw the same error.
StackTrace of error: while executing canGetOverseasTransactiontest
N/A
java.lang.NullPointerException
at com.ingsfundflowservice.activity.GetTransactionsForProcessorGroupActivity.getOverseasTransactions(GetTransactionsForProcessorGroupActivity.java:71)
at com.ingsfundflowservice.activity.GetTransactionsForProcessorGroupActivityTest.canGetOverseasTransactiontest(GetTransactionsForProcessorGroupActivityTest.java:172)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
spring junit mockito abstract-class autowired
I'm writing the Junit test case for a class which is extended by an abstract class. This base abstract class has an autowired object of a different class which is being used in the class I'm testing.
I'm trying to mock in the subclass, but the mocked object is throwing a NullPointerException.
Example:
// class I am testing
public class GetTransactionsForProcessorGroupActivity extends GetTransactionsBaseActivity
private static final Logger log = LogManager.getLogger(GetTransactionsForProcessorGroupActivity.class);
public GetTransactionsForProcessorGroupActivity(ARHFactory arhFactory, MetricsFactory metricsFactory)
super(arhFactory, metricsFactory);
@Override
protected List<OverseasTransaction> getOverseasTransactions(Document herdDocument)
throws IllegalDateFormatException, ProcessorConfigurationException, DocumentException
final String paymentProcessorGroup = HerdDocumentUtils.getPaymentProcessor(herdDocument);
final Date runDate = HerdDocumentUtils.getRunDate(herdDocument);
final List<String> paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup);
List<OverseasTransaction> overseasTransactionList = new ArrayList<OverseasTransaction>();
List<ProcessorTransactionWindow> processingWindows = new ArrayList<ProcessorTransactionWindow>();
for (final String processor : paymentProcessorList)
ProcessorTransactionWindow transactionWindow = ProcessorCalendarUtils.getProcessorTransactionWindow(processor, runDate);
processingWindows.add(transactionWindow);
final Date processingFromDate = transactionWindow.getFromDate();
final Date processingToDate = transactionWindow.getToDate();
//NullpointerException on this line, as OverseasTransactionStore mock object returns null.
final List<OverseasTransaction> transactions = overseasTransactionsStore
.queryOverseasTransactionsOnPPTimelineandDates(processor, processingFromDate, processingToDate);
overseasTransactionList.addAll(transactions);
HerdDocumentUtils.putProcessingWindowDetails(herdDocument, processingWindows);
return overseasTransactionList;
// Base class
public abstract class GetTransactionsBaseActivity extends CoralHerdActivity implements ActionRequestHandler
private static final Logger log = LogManager.getLogger(GetTransactionsBaseActivity.class);
@SuppressWarnings("unchecked")
private static final Map<String, String> S3_CONFIGURATION = AppConfig.findMap(Constants.S3_CONFIGURATION_KEY);
private static final String S3_BUCKET = S3_CONFIGURATION.get(Constants.BUCKET_NAME);
private static final class Status
private static final String PROCESSOR_DETAILS_NOT_FOUND = "NoPaymentProcessorDetailsPresent";
private static final String TRANSACTIONS_OBTAINED = "TransactionsObtained";
private static final String NO_TRANSACTIONS_TO_BE_CONSIDERED = "NoTransactionsToBeConsidered";
private static final String NEGATIVE_OR_ZERO_AMOUNT = "NegativeOrZeroAmount";
protected final ARHFactory arhFactory;
protected final MetricsFactory metricsFactory;
@Autowired
OverseasTransactionsStore overseasTransactionsStore;
@Autowired
S3ClientProvider s3ClientProvider;
protected abstract List<OverseasTransaction> getOverseasTransactions(Document herdDocument)
throws IllegalDateFormatException, ProcessorConfigurationException, DocumentException;
@Override
public ActionResponse postActionRequest(final ActionRequest request) throws Exception
TimedARH timedARH = (TimedARH) arhFactory.createARH();
timedARH.setHandler(this);
return timedARH.handle(request);
public ActionResponse handle(final ActionRequest request) throws Exception
final Document herdDocument = HerdDocumentUtils.getFundFlowDocument(request);
final Metrics metrics = MetricsLogger.getMetrics(metricsFactory);
final String paymentProcessor = HerdDocumentUtils.getPaymentProcessor(herdDocument);
try
final List<OverseasTransaction> overseasTransactionList;
MetricsLogger.logFundFlowExecution(metrics, paymentProcessor);
try
overseasTransactionList = getOverseasTransactions(herdDocument);
catch (ProcessorConfigurationException e)
return new ActionComplete(Status.PROCESSOR_DETAILS_NOT_FOUND, herdDocument);
if (CollectionUtils.isEmpty(overseasTransactionList))
MetricsLogger.logTransactionMetrics(metrics, paymentProcessor, 0, BigDecimal.ZERO);
return new ActionComplete(Status.NO_TRANSACTIONS_TO_BE_CONSIDERED, herdDocument);
final String s3ObjectKey = getS3ObjectKey(request, paymentProcessor);
storeTransactionsInS3(overseasTransactionList, S3_BUCKET, s3ObjectKey);
final int itemCount = overseasTransactionList.size();
BigDecimal totalAmount = BigDecimal.ZERO;
for (OverseasTransaction overseasTransaction : overseasTransactionList)
if (StringUtils.equalsIgnoreCase(overseasTransaction.getType(), Constants.TRANSACTION_TYPE_CHARGE))
totalAmount = totalAmount.add(overseasTransaction.getOverseasAmount());
else if (StringUtils.equalsIgnoreCase(overseasTransaction.getType(), Constants.TRANSACTION_TYPE_REFUND))
totalAmount = totalAmount.subtract(overseasTransaction.getOverseasAmount());
MetricsLogger.logTransactionMetrics(metrics, paymentProcessor, itemCount, totalAmount);
HerdDocumentUtils.putS3Location(herdDocument, S3_BUCKET, s3ObjectKey);
HerdDocumentUtils.putTotalAmount(herdDocument, totalAmount);
HerdDocumentUtils.putTransactionItemCount(herdDocument, itemCount);
HerdDocumentUtils.putPaymentProcessor(herdDocument, paymentProcessor);
if (totalAmount.compareTo(BigDecimal.ZERO) <= 0)
log.info("Total amount to disburse is zero or negative. ", totalAmount);
return new ActionComplete(Status.NEGATIVE_OR_ZERO_AMOUNT, herdDocument);
return new ActionComplete(Status.TRANSACTIONS_OBTAINED, herdDocument);
finally
MetricsLogger.closeMetrics(metrics);
// Test class
@RunWith(PowerMockRunner.class)
@PowerMockIgnore( "javax.management.*" )
@PrepareForTest( HerdDocumentUtils.class, ProcessorGroupLookup.class )
public class GetTransactionsForProcessorGroupActivityTest extends AppConfigInitializedTestBase
private static HerdInput herdInput;
private static HerdOutput herdOutput;
private static final String paymentProcessorGroup = "BillDesk";
private static final String paymentProcessorGroupNotFound = "IndiaPaymentGateway";
@Mock
ActionRequest request;
@Mock
WorkItemIdentifier workItemId;
@Mock
private CoralHerdActivity coralHerdActivity;
@Mock
Metrics metrics;
@Mock
Map<String, String> S3_CONFIGURATION_MAP;
@Mock
MetricsFactory metricsFactory;
@Mock
ARHFactory arhFactory;
@Mock
Document herdDocument;
@Mock
OverseasTransactionsStore overseasTransactionsStore;
@Mock
S3ClientProvider s3ClientProvider;
// @InjectMocks
// GetTransactionsForProcessorGroupActivity getTransactionsBaseActivityTest;
// new GetTransactionsForProcessorGroupActivity(arhFactory, metricsFactory);
@Before
public void setup()
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(HerdDocumentUtils.class);
// PowerMockito.mockStatic(ProcessorGroupLookup.class);
// GetTransactionsBaseActivity getTransactionsBaseActivity = new GetTransactionsBaseActivity(overseasTransactionsStore);
@Test
public void testEnact()
GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity = Mockito
.mock(GetTransactionsForProcessorGroupActivity.class, Mockito.CALLS_REAL_METHODS);
Mockito.when(coralHerdActivity.enact(herdInput)).thenReturn(herdOutput);
final HerdOutput actualHerdOutput = getTransactionsForProcessorGroupActivity.enact(herdInput);
Assert.assertNotNull(actualHerdOutput);
@Test
public void testgetpaymentProcessorList() throws Exception
Date date = new Date();
List<String> paymentProcessorList;
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument)).thenReturn(paymentProcessorGroup);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup);
assertNotNull(paymentProcessorList);
@Test(expected = ProcessorConfigurationException.class)
public void testpaymentProcessorListNotFound()
Date date = new Date();
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument))
.thenReturn(paymentProcessorGroupNotFound);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
List<String> paymentProcessorList = ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroupNotFound);
assertNotNull(paymentProcessorList);
@Test
public void canGetOverseasTransactiontest() throws Exception
GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity = Mockito
.mock(GetTransactionsForProcessorGroupActivity.class);
// OverseasTransactionsStore overseasTransactionsStore =
// Mockito.mock(OverseasTransactionsStoreImpl.class);
Date date = new Date();
MockitoAnnotations.initMocks(this);
PowerMockito.when(HerdDocumentUtils.getPaymentProcessor(herdDocument)).thenReturn(paymentProcessorGroup);
PowerMockito.when(HerdDocumentUtils.getRunDate(herdDocument)).thenReturn(date);
// List<String> paymentProcessorList = new ArrayList<>();
// paymentProcessorList.add("BillDesk");
// PowerMockito.when(ProcessorGroupLookup.getProcessorsFromGroup(paymentProcessorGroup))
// .thenReturn(paymentProcessorList);
String fromDate = "Sat Mar 16 23:59:59 IST 2019";
String toDate = "Sat Mar 16 23:59:59 IST 2019";
DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
List<OverseasTransaction> overseasTransactionList1 = createMockOverseasTransaction();
Mockito.doReturn(overseasTransactionList1).when(overseasTransactionsStore)
.queryOverseasTransactionsOnPPTimelineandDates(Mockito.isA(String.class), Mockito.isA(Date.class),
Mockito.isA(Date.class));
Mockito.when(getTransactionsForProcessorGroupActivity.getOverseasTransactions(herdDocument))
.thenCallRealMethod();
List<OverseasTransaction> overseasTransactionList = getTransactionsForProcessorGroupActivity
.getOverseasTransactions(herdDocument);
assertNotNull(overseasTransactionList);
// assertEquals(overseasTransactionList.getPaymentProcessorID(), actual);
private List<OverseasTransaction> createMockOverseasTransaction()
Date date = new Date();
BigDecimal num = new BigDecimal(100001);
List<OverseasTransaction> overseasTransactionList = new ArrayList<OverseasTransaction>();
OverseasTransaction overseasTransaction = new OverseasTransaction();
overseasTransaction.setPurchaseID("purchaseID");
overseasTransaction.setSignatureID("signatureID");
overseasTransaction.setPaymentProcessorTransactionID("paymentProcessorTransactionID");
overseasTransaction.setType("Charge");
overseasTransaction.setSubType("subType");
overseasTransaction.setTransactionTimestamp(date);
overseasTransaction.setPaymentMethod("paymentMethod");
overseasTransaction.setTotalAmount(num);
overseasTransaction.setOverseasAmount(num);
overseasTransaction.setCurrency("currency");
overseasTransaction.setMarketplaceID("marketplaceID");
overseasTransaction.setOrderMetadata("orderMetadata");
overseasTransaction.setDisbursementID("disbursementID");
overseasTransaction.setReconState(1);
overseasTransaction.setPaymentProcessorID("BillDesk");
overseasTransaction.setRemittanceFileStatus("remittanceFileStatus");
overseasTransaction.setCrowID("crowID");
overseasTransaction.setSource("source");
overseasTransactionList.add(overseasTransaction);
return overseasTransactionList;
In my test file when I mock OverseasTransaction object, it gives me a NullPointerException. Do you have any suggestions about how we can mock this? All the above commented lines in my test indicates the things I tried but they still seem to throw the same error.
StackTrace of error: while executing canGetOverseasTransactiontest
N/A
java.lang.NullPointerException
at com.ingsfundflowservice.activity.GetTransactionsForProcessorGroupActivity.getOverseasTransactions(GetTransactionsForProcessorGroupActivity.java:71)
at com.ingsfundflowservice.activity.GetTransactionsForProcessorGroupActivityTest.canGetOverseasTransactiontest(GetTransactionsForProcessorGroupActivityTest.java:172)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
spring junit mockito abstract-class autowired
spring junit mockito abstract-class autowired
edited Mar 23 at 7:47
Shefali Chaudhary
asked Mar 22 at 16:01
Shefali ChaudharyShefali Chaudhary
104
104
My all imports and @prepareForTest annotations are in place. I have also initialized my Mocks in Before using Mockito.init(this).
– Shefali Chaudhary
Mar 22 at 16:02
First of all, removePowerMockito.Mock
, just dowhen(overseastransaction.somemethod()).thenReturn(something)
, this is how you define behavior. Second, how are you injecting the mock in your object under test?
– Morfic
Mar 22 at 16:14
add a comment |
My all imports and @prepareForTest annotations are in place. I have also initialized my Mocks in Before using Mockito.init(this).
– Shefali Chaudhary
Mar 22 at 16:02
First of all, removePowerMockito.Mock
, just dowhen(overseastransaction.somemethod()).thenReturn(something)
, this is how you define behavior. Second, how are you injecting the mock in your object under test?
– Morfic
Mar 22 at 16:14
My all imports and @prepareForTest annotations are in place. I have also initialized my Mocks in Before using Mockito.init(this).
– Shefali Chaudhary
Mar 22 at 16:02
My all imports and @prepareForTest annotations are in place. I have also initialized my Mocks in Before using Mockito.init(this).
– Shefali Chaudhary
Mar 22 at 16:02
First of all, remove
PowerMockito.Mock
, just do when(overseastransaction.somemethod()).thenReturn(something)
, this is how you define behavior. Second, how are you injecting the mock in your object under test?– Morfic
Mar 22 at 16:14
First of all, remove
PowerMockito.Mock
, just do when(overseastransaction.somemethod()).thenReturn(something)
, this is how you define behavior. Second, how are you injecting the mock in your object under test?– Morfic
Mar 22 at 16:14
add a comment |
1 Answer
1
active
oldest
votes
You need to create object of Class which for which you are writing the test. i.e. GetTransactionsForProcessorGroupActivity. There is what you can do
@RunWith(MockitoJUnitRunner.class)
public class GetTransactionsForProcessorGroupActivityTest
@InjectMocks
private GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity;
@Mock
private OverseasTransaction overseastransaction;
@Test
public void test()
Mockito.when(overseastransaction.somemethod()).thenReturn(something);
This will make sure that getTransactionsForProcessorGroupActivity is created and overseastransaction is injected with mock object.
Please note the class annotation @RunWith. This make sure that all the properties are injected with mock object properly. Also, you can use Mockito instead of PowerMockito.
I am using @RunWith(PowerMockRunner.class) since there are other static methods in this class which I want to mock. Also it is not able to create the object of class GetTransactionsForProcessorGroupActivity which I try to Inject Mocks. Maybe because it extends and abstract class and you can not instantiate an abstract class.
– Shefali Chaudhary
Mar 22 at 17:20
GetTransactionsForProcessorGroupActivity is a concrete class, so object creation will work (does not matter if its extends an abstract class or implement an interface). One can create object Either directly using new or using Mock. Can you update the answer to include the whole code snippet ? Also, can you paste the complete stack trace of error you are getting.
– lrathod
Mar 23 at 7:08
Yes, But I am unable to create one. I have update the whole code snippet.
– Shefali Chaudhary
Mar 23 at 7:50
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55303553%2fmocking-an-autowired-object-of-base-abstract-class%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You need to create object of Class which for which you are writing the test. i.e. GetTransactionsForProcessorGroupActivity. There is what you can do
@RunWith(MockitoJUnitRunner.class)
public class GetTransactionsForProcessorGroupActivityTest
@InjectMocks
private GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity;
@Mock
private OverseasTransaction overseastransaction;
@Test
public void test()
Mockito.when(overseastransaction.somemethod()).thenReturn(something);
This will make sure that getTransactionsForProcessorGroupActivity is created and overseastransaction is injected with mock object.
Please note the class annotation @RunWith. This make sure that all the properties are injected with mock object properly. Also, you can use Mockito instead of PowerMockito.
I am using @RunWith(PowerMockRunner.class) since there are other static methods in this class which I want to mock. Also it is not able to create the object of class GetTransactionsForProcessorGroupActivity which I try to Inject Mocks. Maybe because it extends and abstract class and you can not instantiate an abstract class.
– Shefali Chaudhary
Mar 22 at 17:20
GetTransactionsForProcessorGroupActivity is a concrete class, so object creation will work (does not matter if its extends an abstract class or implement an interface). One can create object Either directly using new or using Mock. Can you update the answer to include the whole code snippet ? Also, can you paste the complete stack trace of error you are getting.
– lrathod
Mar 23 at 7:08
Yes, But I am unable to create one. I have update the whole code snippet.
– Shefali Chaudhary
Mar 23 at 7:50
add a comment |
You need to create object of Class which for which you are writing the test. i.e. GetTransactionsForProcessorGroupActivity. There is what you can do
@RunWith(MockitoJUnitRunner.class)
public class GetTransactionsForProcessorGroupActivityTest
@InjectMocks
private GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity;
@Mock
private OverseasTransaction overseastransaction;
@Test
public void test()
Mockito.when(overseastransaction.somemethod()).thenReturn(something);
This will make sure that getTransactionsForProcessorGroupActivity is created and overseastransaction is injected with mock object.
Please note the class annotation @RunWith. This make sure that all the properties are injected with mock object properly. Also, you can use Mockito instead of PowerMockito.
I am using @RunWith(PowerMockRunner.class) since there are other static methods in this class which I want to mock. Also it is not able to create the object of class GetTransactionsForProcessorGroupActivity which I try to Inject Mocks. Maybe because it extends and abstract class and you can not instantiate an abstract class.
– Shefali Chaudhary
Mar 22 at 17:20
GetTransactionsForProcessorGroupActivity is a concrete class, so object creation will work (does not matter if its extends an abstract class or implement an interface). One can create object Either directly using new or using Mock. Can you update the answer to include the whole code snippet ? Also, can you paste the complete stack trace of error you are getting.
– lrathod
Mar 23 at 7:08
Yes, But I am unable to create one. I have update the whole code snippet.
– Shefali Chaudhary
Mar 23 at 7:50
add a comment |
You need to create object of Class which for which you are writing the test. i.e. GetTransactionsForProcessorGroupActivity. There is what you can do
@RunWith(MockitoJUnitRunner.class)
public class GetTransactionsForProcessorGroupActivityTest
@InjectMocks
private GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity;
@Mock
private OverseasTransaction overseastransaction;
@Test
public void test()
Mockito.when(overseastransaction.somemethod()).thenReturn(something);
This will make sure that getTransactionsForProcessorGroupActivity is created and overseastransaction is injected with mock object.
Please note the class annotation @RunWith. This make sure that all the properties are injected with mock object properly. Also, you can use Mockito instead of PowerMockito.
You need to create object of Class which for which you are writing the test. i.e. GetTransactionsForProcessorGroupActivity. There is what you can do
@RunWith(MockitoJUnitRunner.class)
public class GetTransactionsForProcessorGroupActivityTest
@InjectMocks
private GetTransactionsForProcessorGroupActivity getTransactionsForProcessorGroupActivity;
@Mock
private OverseasTransaction overseastransaction;
@Test
public void test()
Mockito.when(overseastransaction.somemethod()).thenReturn(something);
This will make sure that getTransactionsForProcessorGroupActivity is created and overseastransaction is injected with mock object.
Please note the class annotation @RunWith. This make sure that all the properties are injected with mock object properly. Also, you can use Mockito instead of PowerMockito.
answered Mar 22 at 16:23
lrathodlrathod
454313
454313
I am using @RunWith(PowerMockRunner.class) since there are other static methods in this class which I want to mock. Also it is not able to create the object of class GetTransactionsForProcessorGroupActivity which I try to Inject Mocks. Maybe because it extends and abstract class and you can not instantiate an abstract class.
– Shefali Chaudhary
Mar 22 at 17:20
GetTransactionsForProcessorGroupActivity is a concrete class, so object creation will work (does not matter if its extends an abstract class or implement an interface). One can create object Either directly using new or using Mock. Can you update the answer to include the whole code snippet ? Also, can you paste the complete stack trace of error you are getting.
– lrathod
Mar 23 at 7:08
Yes, But I am unable to create one. I have update the whole code snippet.
– Shefali Chaudhary
Mar 23 at 7:50
add a comment |
I am using @RunWith(PowerMockRunner.class) since there are other static methods in this class which I want to mock. Also it is not able to create the object of class GetTransactionsForProcessorGroupActivity which I try to Inject Mocks. Maybe because it extends and abstract class and you can not instantiate an abstract class.
– Shefali Chaudhary
Mar 22 at 17:20
GetTransactionsForProcessorGroupActivity is a concrete class, so object creation will work (does not matter if its extends an abstract class or implement an interface). One can create object Either directly using new or using Mock. Can you update the answer to include the whole code snippet ? Also, can you paste the complete stack trace of error you are getting.
– lrathod
Mar 23 at 7:08
Yes, But I am unable to create one. I have update the whole code snippet.
– Shefali Chaudhary
Mar 23 at 7:50
I am using @RunWith(PowerMockRunner.class) since there are other static methods in this class which I want to mock. Also it is not able to create the object of class GetTransactionsForProcessorGroupActivity which I try to Inject Mocks. Maybe because it extends and abstract class and you can not instantiate an abstract class.
– Shefali Chaudhary
Mar 22 at 17:20
I am using @RunWith(PowerMockRunner.class) since there are other static methods in this class which I want to mock. Also it is not able to create the object of class GetTransactionsForProcessorGroupActivity which I try to Inject Mocks. Maybe because it extends and abstract class and you can not instantiate an abstract class.
– Shefali Chaudhary
Mar 22 at 17:20
GetTransactionsForProcessorGroupActivity is a concrete class, so object creation will work (does not matter if its extends an abstract class or implement an interface). One can create object Either directly using new or using Mock. Can you update the answer to include the whole code snippet ? Also, can you paste the complete stack trace of error you are getting.
– lrathod
Mar 23 at 7:08
GetTransactionsForProcessorGroupActivity is a concrete class, so object creation will work (does not matter if its extends an abstract class or implement an interface). One can create object Either directly using new or using Mock. Can you update the answer to include the whole code snippet ? Also, can you paste the complete stack trace of error you are getting.
– lrathod
Mar 23 at 7:08
Yes, But I am unable to create one. I have update the whole code snippet.
– Shefali Chaudhary
Mar 23 at 7:50
Yes, But I am unable to create one. I have update the whole code snippet.
– Shefali Chaudhary
Mar 23 at 7:50
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55303553%2fmocking-an-autowired-object-of-base-abstract-class%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
My all imports and @prepareForTest annotations are in place. I have also initialized my Mocks in Before using Mockito.init(this).
– Shefali Chaudhary
Mar 22 at 16:02
First of all, remove
PowerMockito.Mock
, just dowhen(overseastransaction.somemethod()).thenReturn(something)
, this is how you define behavior. Second, how are you injecting the mock in your object under test?– Morfic
Mar 22 at 16:14