//This is my Main Class here when i call methodTwo in this class i got numnodes=4 but when i tried to access methodTwo in testclass i got NullPointerException.
package Netica;
import norsys.netica.Environ;
import norsys.netica.Net;
import norsys.netica.NodeList;
import norsys.netica.Streamer;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import NeticaTestCases.HNetTest;
public class HNet {
private static long startTime = System.currentTimeMillis();
private static Net net;
private static NodeList nodes;
int numNodes;
public int methodOne() {
System.out.println("we are in first methodOne");
return 1;
}
public int methodTwo() {
numNodes = nodes.size();
System.out.println("we are in 2nd methodTwo");
return numNodes;
}
public static void main(String[] args) {
try {
// Read in the net file and get list of all nodes and also Total
// number of nodes:
net = new Net(neStreamer("DataFiles/KSA_4_Nodes_noisySum.dne"));
nodes = net.getNodes();
HNet temp = new HNet();
temp.methodOne();
System.out.println("numNodes========>"+temp.methodTwo());//get 4
} catch (Exception e) {
}
}
}
//this is my testclass
package NeticaTestCases;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.fail;
import Netica.HNet;
public class HNetTest {
HNet temp;
#Before
public void setUp() {
temp = new HNet ();
}
#Test
public void CheckNumNodes() {
temp.methodOne();
System.out.println("numNodes========>"+temp.methodTwo());
}
}
please help me out how to resolve NullPointerException in junit testcases.
Adding a statement initialising the nodes should get you rid of the exception -
#Before
public void setUp() {
temp = new HNet ();
temp.nodes = new NodeList();
}
Also, would suggest you to try and improve on few points -
Debug the difference between your main method and CheckNumNodes() test method.
Use of getters and setters
Related
I am trying to use Soot to perform data flow analysis on a java file which is called Example.java.
Here is my Example.java file, my goal is to know which saySomething method animal.saySomething() will call. Here is the code for Example.java I am using:
package a1;
public class Example {
static Animal neverCalled() {
return new Fish();
}
static Animal selectAnimal() {
return new Cat();
}
public static void main(String[] args) {
Animal animal = selectAnimal();
animal.saySomething();
}
}
abstract class Animal {
public abstract void saySomething();
}
class Cat extends Animal {
public void saySomething() {
System.out.println("purr");
}
}
class Dog extends Animal {
public void saySomething() {
System.out.println("woof");
}
}
class Fish extends Animal {
public void saySomething() {
System.out.println("...");
}
}
class Car { // not an Animal
public void saySomething() {
System.out.println("honk!");
}
}
and here is the code I am using to analyze Example.java using Soot, this code is located in the file: TestSootCallGraph.java which follows here:
package a1;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import soot.*;
import soot.jimple.Stmt;
import soot.jimple.spark.SparkTransformer;
import soot.jimple.toolkits.callgraph.CHATransformer;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Targets;
import soot.options.Options;
public class TestSootCallGraph extends SceneTransformer {
static LinkedList<String> excludeList;
public static void main(String[] args) {
String mainclass = "Example";
// //set classpath
String javapath = System.getProperty("java.class.path");
String jredir = System.getProperty("java.home")+"/lib/rt.jar";
String path = javapath+File.pathSeparator+jredir;
Scene.v().setSootClassPath(path);
//add an intra-procedural analysis phase to Soot
TestSootCallGraph analysis = new TestSootCallGraph();
PackManager.v().getPack("wjtp").add(new Transform("wjtp.TestSootCallGraph", analysis));
excludeJDKLibrary();
//whole program analysis
Options.v().set_whole_program(true);
//load and set main class
Options.v().set_app(true);
SootClass appclass = Scene.v().loadClassAndSupport(mainclass);
System.out.println(appclass);
Scene.v().setMainClass(appclass);
Scene.v().loadNecessaryClasses();
//enable call graph
//enableCHACallGraph();
//enableSparkCallGraph();
//start working
PackManager.v().runPacks();
}
private static void excludeJDKLibrary()
{
//exclude jdk classes
Options.v().set_exclude(excludeList());
//this option must be disabled for a sound call graph
Options.v().set_no_bodies_for_excluded(true);
Options.v().set_allow_phantom_refs(true);
}
private static void enableSparkCallGraph() {
//Enable Spark
HashMap<String,String> opt = new HashMap<String,String>();
//opt.put("propagator","worklist");
//opt.put("simple-edges-bidirectional","false");
opt.put("on-fly-cg","true");
//opt.put("set-impl","double");
//opt.put("double-set-old","hybrid");
//opt.put("double-set-new","hybrid");
//opt.put("pre_jimplify", "true");
SparkTransformer.v().transform("",opt);
PhaseOptions.v().setPhaseOption("cg.spark", "enabled:true");
}
private static void enableCHACallGraph() {
CHATransformer.v().transform();
}
private static LinkedList<String> excludeList()
{
if(excludeList==null)
{
excludeList = new LinkedList<String> ();
excludeList.add("java.");
excludeList.add("javax.");
excludeList.add("sun.");
excludeList.add("sunw.");
excludeList.add("com.sun.");
excludeList.add("com.ibm.");
excludeList.add("com.apple.");
excludeList.add("apple.awt.");
}
return excludeList;
}
#Override
protected void internalTransform(String phaseName,
Map options) {
int numOfEdges =0;
CallGraph callGraph = Scene.v().getCallGraph();
for(SootClass sc : Scene.v().getApplicationClasses()){
for(SootMethod m : sc.getMethods()){
Iterator<MethodOrMethodContext> targets = new Targets(
callGraph.edgesOutOf(m));
while (targets.hasNext()) {
numOfEdges++;
SootMethod tgt = (SootMethod) targets.next();
System.out.println(m + " may call " + tgt);
}
}
}
System.err.println("Total Edges:" + numOfEdges);
}
}
I receive the following error when executing TestSootCallGraph.java which aims at analyzing Example.java. How can I fix this?
Example
Exception in thread "main" java.lang.RuntimeException: Main-class has no main method!
at soot.Scene.setMainClass(Scene.java:171)
at a1.TestSootCallGraph.main(TestSootCallGraph.java:47)
MyEvent extends EventObject.
public class MyEvent extends EventObject {
private int buttonName;
public void setNum( int num) {
this.num= num;
}
public int getNum(){
return num;
}
public MyEvent(Object source) {
super(source);
}
}
With mockito-all-2.0.2-beta, I do mock the above Event for a unit test
import org.junit.After;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.mock;
public class MyEventTest {
public MyEventTest() {
}
#Before
public void setUp() {
}
#After
public void tearDown() {
}
/**
* Test of getButtonNum method, of class MyEvent.
*/
#Test
public void testGetButtonNumEqual() {
System.out.println("setButtonNum");
MyEvent evt = mock(MyEvent.class);
int buttonNum = 1;
evt.setButtonNum(buttonNum);
int result = evt.getButtonNum();
System.out.println(buttonNum);
System.out.println(result);
assertEquals(buttonNum, result);
}
/**
* Test of getButtonNum method, of class MyEvent.
*/
#Test
public void testGetButtonNumNotEqual() {
System.out.println("setButtonNum");
MyEvent evt = mock(MyEvent.class);
int buttonNum = 2;
int notEqualNum = 1;
evt.setButtonNum(buttonNum);
int result = evt.getButtonNum();
System.out.println(buttonNum);
System.out.println(result);
assertNotEquals(notEqualNum, result);
}
}
First Test is failed and Second Test is passed. The print output is below.
{
setButtonNum
1
0
and
setButtonNum
2
0
}
I would like to know why the first test is fail and how to do unit test a custom event.
Please, let me know what mistake I did. I appreciate your help. Thanks.
I want to mock a private method which has been called inside another method.
Following is the sample code, I have written.
Java code:
package org.mockprivatemethods;
public class AccountDeposit {
// Instantiation of AccountDetails using some DI
AccountDetails accountDetails;
public long deposit(long accountNum, long amountDeposited){
long amount = 0;
try{
amount = accountDetails.getAmount(accountNum);
updateAccount(accountNum, amountDeposited);
amount= amount + amountDeposited;
} catch(Exception e){
// log exception
}
return amount;
}
private void updateAccount(long accountNum, long amountDeposited) throws Exception {
// some database operation to update amount in the account
}
// for testing private methods
private int sum(int num1, int num2){
return num1+num2;
}
}
class AccountDetails{
public long getAmount(long accountNum) throws Exception{
// some database operation returning amount in the account
long amount = 10000L;
return amount;
}
}
Testclass:
package org.mockprivatemethods;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
#RunWith(PowerMockRunner.class)
public class TestAccountDeposit {
#InjectMocks
AccountDeposit accountDeposit;
#Mock
AccountDetails accountDetailsMocks;
#Test
public void testDposit() throws Exception{
long amount = 200;
when(accountDetailsMocks.getAmount(Mockito.anyLong()))
.thenReturn(amount);
// need to mock private method updateAccount
// just like we tested the private method "sum()" using Whitebox
// How to mock this private method updateAccount
long totalAmount = accountDeposit.deposit(12345678L, 50);
assertTrue("Amount in Account(200+50): "+totalAmount , 250==totalAmount);
}
#Test
public void testSum(){
try {
int amount = Whitebox.invokeMethod(accountDeposit, "sum", 20, 30);
assertTrue("Sum of (20,30): "+amount, 50==amount);
} catch (Exception e) {
Assert.fail("testSum() failed with following error: "+e);
}
}
}
We can test the private methods using Whitebox.invokeMethod(). My question is: Is there any to way mock the private method using Whitebox. Can we write something similar to below code to mock the updateAccount() as I do not want any database operation to be performed while testing the Deposit() method?strong text
when(accountDetailsMocks.getAmount(Mockito.anyLong()))
.thenReturn(amount);
Any help is appreciated! Thanks!
I am having this error while all my methods in this test are successful - all of them return true. Also tried to make boolean for each method call and use only one call for assertTrue(a && b && c && d && e).
I run the junit test in java - netbeans.
My junit code (first time using junit) is:
package redis_fast_algo;
import data_sets.FastSortAlgoData;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class FastSortAlgoStudyTest {
private DataMaker dataMake;
private final static boolean BEFORE_DELETE = false;
public FastSortAlgoStudyTest() {
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
dataMake = new DataMaker();
}
#After
public void tearDown() {
}
/**
* Test of study method, of class FastSortAlgoStudy.
*/
#Test
public void testStudy() throws Exception {
System.out.println("study");
FastSortAlgoData data = dataMake.getData(5);
FastSortAlgoStudy instance = new FastSortAlgoStudy(data);
FastSortAlgoTest testStudy = new FastSortAlgoTest(data);
testStudy.prepareForTest();
instance.study();
assertTrue(testStudy.testCheckFolderStudyCounter(BEFORE_DELETE));
assertTrue(testStudy.testCheckBodyPart(BEFORE_DELETE));
assertTrue(testStudy.testCheckTitlePart(BEFORE_DELETE));
assertTrue(testStudy.testCheckFoldersHistoryWithData(BEFORE_DELETE));
assertTrue(testStudy.testRemoveFolderHistory());
}
}
From the examples on the PowerMock homepage, I see the following example for partially mocking a private method with Mockito:
#RunWith(PowerMockRunner.class)
// We prepare PartialMockClass for test because it's final or we need to mock private or static methods
#PrepareForTest(PartialMockClass.class)
public class YourTestCase {
#Test
public void privatePartialMockingWithPowerMock() {
PartialMockClass classUnderTest = PowerMockito.spy(new PartialMockClass());
// use PowerMockito to set up your expectation
PowerMockito.doReturn(value).when(classUnderTest, "methodToMock", "parameter1");
// execute your test
classUnderTest.execute();
// Use PowerMockito.verify() to verify result
PowerMockito.verifyPrivate(classUnderTest, times(2)).invoke("methodToMock", "parameter1");
}
However, this approach does not seem to work when the private method we wish to mock is static. I wish to create a partial mock of the below class, with the readFile method mocked:
package org.rich.powermockexample;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import static com.google.common.io.Files.readLines;
public class DataProvider {
public static List<String> getData() {
List<String> data = null;
try {
data = readFile();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
private static List<String> readFile() throws IOException {
File file = new File("/some/path/to/file");
List<String> lines = readLines(file, Charset.forName("utf-8"));
return lines;
}
}
Please could someone let me know how this can be achieved?
After doing a bit more research, it seems that PowerMockito.spy() and PowerMockito.doReturn() are what is required here:
package com.richashworth.powermockexample;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
#RunWith(PowerMockRunner.class)
#PrepareForTest({DataProvider.class})
public class ResultsWriterTest {
private static List<String> mockData = new ArrayList<String>();
private ResultsWriter resultsWriter;
#BeforeClass
public static void setUpOnce() {
final String firstLine = "Line 1";
final String secondLine = "Line 2";
mockData.add(firstLine);
mockData.add(secondLine);
}
#Before
public void setUp() {
resultsWriter = new ResultsWriter();
}
#Test
public void testGetDataAsString() throws Exception {
PowerMockito.spy(DataProvider.class);
PowerMockito.doReturn(mockData).when(DataProvider.class, "readFile");
final String expectedData = "Line 1\nLine 2\n";
final String returnedString = resultsWriter.getDataAsString();
assertEquals(expectedData, returnedString);
}
}
For further details and the complete code listing, check out my blog post here: https://richashworth.com/post/turbocharge-your-mocking-framework-with-powermock/
Test class:
#RunWith(PowerMockRunner.class)
#PrepareForTest(DataProvider.class)
public class DataProviderTest {
#Test
public void testGetDataWithMockedRead() throws Exception {
mockStaticPartial(DataProvider.class, "readFile");
Method[] methods = MemberMatcher.methods(DataProvider.class, "readFile");
expectPrivate(DataProvider.class, methods[0]).andReturn(Arrays.asList("ohai", "kthxbye"));
replay(DataProvider.class);
List<String> theData = DataProvider.getData();
assertEquals("ohai", theData.get(0));
assertEquals("kthxbye", theData.get(1));
}
}
Class being tested (basically yours):
public class DataProvider {
public static List<String> getData() {
try {
return readFile();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static List<String> readFile() throws IOException {
File file = new File("/some/path/to/file");
return readLines(file, Charset.forName("utf-8"));
}
}
In general, only use static mocking for classes that are beyond your control (e.g. java.io.File). Since DataProvider and readFile are your own, refactor DataProvider into a proper class (i.e. make its methods non-static), pull out readFile into a helper object and then mock that. See this answer https://stackoverflow.com/a/8819339/116509.