JUnit test giving NullPointerException - java

One of my JUnit tests is giving me a NullPointerException and I can't figure out why.
This is the contents of the test class, PacketWrapperTest:
/**
* Mock Node for Packet A.
*/
private Node nA;
/**
* Packet A.
*/
private PacketWrapper packetA;
/**
* Mock Node for Packet B.
*/
private Node nB;
/**
* Packet B.
*/
private PacketWrapper packetB;
/**
* Relationship A
*/
Relationship RelA;
/**
* Relationship B
*/
Relationship RelB;
#Before
public void setup() {
nA = mock(Node.class);
nB = mock(Node.class);
packetA = new PacketWrapper(nA);
packetB = new PacketWrapper(nB);
RelA = mock(Relationship.class);
RelB = mock(Relationship.class);
}
#After
public void tearDown() {
packetA = null;
packetB = null;
}
/*
* ---------------- Test hashContents() ---------------
*/
#Test
public void testHashContents() {//TODO: Fix
when(nA.getProperty(PacketWrapper.KEY_CONTENTS)).thenReturn(new byte[] {1});
packetA.hashContents();
verify(nA).setProperty(PacketWrapper.KEY_CONTENTS, packetA.getContents().hashCode());
verify(nA).setProperty(PacketWrapper.IS_HASH, true);
}
This is the relevant contents of PacketWrapperTest:
/**
* DB key for the contents property.
*/
static final String KEY_CONTENTS = "contents";
/**
* DB key for the is_hashed property.
*/
static final String IS_HASH = "is_hashed";
/**
* Underlying neo4j node.
*/
private final Node neo4jNode;
/**
* Creates a new Packet wrapping the specified node
*
* #param neo4jNode
* underlying neo4j node.
*/
public PacketWrapper(Node neo4jnode) {
this.neo4jNode = neo4jnode;
}
#Override
public byte[] getContents() {
return (byte []) neo4jNode.getProperty(KEY_CONTENTS);
}
#Override
public void setContents(byte[] newContents) {
neo4jNode.setProperty(KEY_CONTENTS, newContents);
}
#Override
public void hashContents() {
neo4jNode.setProperty(KEY_CONTENTS, ((byte[])getContents()).hashCode());
neo4jNode.setProperty(IS_HASH, true);
}
#Override
public int hashCode() {
return neo4jNode.hashCode();
}
And here is the stack trace:
java.lang.NullPointerException
at org.whispercomm.manes.server.graph.PacketWrapperTest.testHashContents(PacketWrapperTest.java:124)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Although Java didn't give me that long of a stack trace for some reason, I only had the first two lines and saw the rest when I copied and pasted...
EDIT: Sorry, forgot to mention line 124 is
verify(nA).setProperty(PacketWrapper.KEY_CONTENTS, packetA.getContents().hashCode());
Also, I'm using the neo4j libraries.
EDIT2: After adding in some debugging statements this is the test code:
#Test
public void testHashContents() {//TODO: Fix
byte[] testByte = new byte[] {1};
when(nA.getProperty(PacketWrapper.KEY_CONTENTS)).thenReturn(testByte);
packetA.hashContents();
System.out.println(testByte.hashCode());
System.out.println(packetA.getContents());
System.out.println(packetA.getContents().hashCode());
verify(nA, times(3)).setProperty(PacketWrapper.KEY_CONTENTS, packetA.getContents().hashCode());
verify(nA).setProperty(PacketWrapper.IS_HASH, true);
}
And this is the output:
26281671
[B#19106c7
26281671
The line:
verify(nA, times(3)).setProperty(PacketWrapper.KEY_CONTENTS, packetA.getContents().hashCode());
is throwing the exception.

Line 124 would have to be one of these:
when(nA.getProperty(PacketWrapper.KEY_CONTENTS)).thenReturn(new byte[] {1});
packetA.getContents().hashCode()
verify(nA).setProperty(PacketWrapper.KEY_CONTENTS, packetA.getContents().hashCode());
If verify(nA) or when(...) returns null, then those lines would NPE; if the property KEY_CONTENTS is not defined, then the second will throw an NPE. Other lines would give stack traces with other methods on top. There are too many different ways where these things could go wrong, all having to do with other code not shown here; you'll have to track this down yourself.

In the statement
verify(nA).setProperty(KEY_CONTENTS, packetA.getContents().hashCode());
you are actually calling hashCode on nA (through delegation) before you are calling setProperty which is confusing Mockito as to which method is being verified. Change your test to
#Test
public void testHashContents() {//TODO: Fix
when(nA.getProperty(PacketWrapper.KEY_CONTENTS)).thenReturn(new byte[] {1});
packetA.hashContents();
int hash = packetA.getContents().hashCode();
verify(nA).setProperty(PacketWrapper.KEY_CONTENTS, hash);
verify(nA).setProperty(PacketWrapper.IS_HASH, true);
}
and you will see it passes.

Related

Java - JUnit how to do?

I have the following method and how can I do the JUnit testing on it?
Parser is my constructor, which I am also using as my return type of my following method.
As this method is splitting the string in three one, so for that I want to write a unit test case.
I am somehow familiar with JUnit but not that much. Any guidance/ link/ help will be appreciated.
public class Example {
public Parser thirdValueCleanup(String value) {
String thirdValueValue = value.trim();
System.out.println("TestData: "+thirdValueValue);
String firstValueRegex = "[A-z]\\d[A-z]";
String secondValueRegex = "\\d[A-z]\\d";
String thirdValueRegex = "[SK|sk]{2}";
Pattern firstValuePattern = Pattern.compile(".*\\W*("+firstValueRegex+")\\W*.*");
Pattern secondValuePattern = Pattern.compile(".*\\W*("+secondValueRegex+")\\W*.*");
Pattern thirdValuePattern = Pattern.compile(".*\\W*("+thirdValueRegex+")\\W*.*");
String firstValue = "";
String secondValue = "";
String thirdValue = "";
Matcher firstValueMatcher = firstValuePattern.matcher(thirdValueValue);
if(firstValueMatcher.matches()) {
firstValue = firstValueMatcher.group(1);
}
Matcher secondValueMatcher = secondValuePattern.matcher(thirdValueValue);
if(secondValueMatcher.matches()) {
secondValue = secondValueMatcher.group(1);
}
Matcher thirdValueMatcher = thirdValuePattern.matcher(thirdValueValue);
if(thirdValueMatcher.matches()) {
thirdValue = thirdValueMatcher.group(1);
}
String FirstValueName = firstValue + " " + secondValue;
String thirdValueName = thirdValue;
return new Parser(FirstValueName, thirdValueName);
}
public Parser(String firstValue, String secondValue) {
this.firstValue = firstValue;
this.secondValue = secondValue;
}
public String getFirstValue() {
return firstValue;
}
public String getSecondValue() {
return secondValue;
}
}
I tried in my test:
public final void testThirdValueCleanup() {
System.out.println("retrieve");
String factories = "SK S6V 7L4";
Parser parser = new Parser();
Parser expResult = SK S6V 7L4;
Parser result = parser.thirdValueCleanup(factories);
assertEquals(expResult, result);
}
I got this error:
junit.framework.AssertionFailedError: expected:<SK S6V 7L4> but was:<com.example.Parser#379619aa>
at junit.framework.Assert.fail(Assert.java:57)
at junit.framework.Assert.failNotEquals(Assert.java:329)
at junit.framework.Assert.assertEquals(Assert.java:78)
at junit.framework.Assert.assertEquals(Assert.java:86)
at junit.framework.TestCase.assertEquals(TestCase.java:253)
at com.example.ParserTest.testthirdValueCleanup(ParserTest.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:252)
at junit.framework.TestSuite.run(TestSuite.java:247)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
try this
#Test
public final void testThirdValue() {
System.out.println("retrieve");
String factories = " BK M6B 7A4";
Parser parser = new Parser();
Parser province = parser.thirdValue(factories);
assertEquals("M6B 7A4", province.getFirstValue());
assertEquals("BK", province.getSecondValue());
}
Any guidance/ link/ help will be appreciated. thanks
As a simple approach, you might want to try out something within the following lines. As a first step create the test class:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ExampleTest {
Example example = new Example();
#Test
public void testThirdValueCleanup(){
//pass some inputs to your function
//by exclicitly calling
//example.thirdValueCleanup(input params...);
//a simple test case would be to check if it you get what your expect
Parser expected = new Parser("set this one as it should be");
assertEquals(example.thirdValueCleanup(some inputs...), expected);
}
/*
* Here you can define more test cases
*/
}
Next you can create a class to run your test:
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(ExampleTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
For more information you can consult either this tutorial or getting started by JUnit.

Java JUnit Test - Java.Lang.NullPointerException [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am quite new to Java and JUnit testing and am very confused with an error I am getting. The error, Null Pointer exception as the code below I am guessing is because something is equal to null but i am unsure why.
java.lang.NullPointerException
at com.nsa.y1.trafficlights.FourWayJunctionTest.PhaseOneInitiation(FourWayJunctionTest.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:109)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:377)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745) com.nsa.y1.trafficlights.FourWayJunctionTest > PhaseOneInitiation FAILED
java.lang.NullPointerException at FourWayJunctionTest.java:47
Here is the test file:
package com.nsa.y1.trafficlights;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by c167 on 12/03/2017.
*/
public class FourWayJunctionTest {
private Light greenLight, amberLight, redLight, greenRightArrow, greenLeftArrow;
private FourLightTrafficLight turnRightTrafficLight;
boolean lightStateRed;
boolean lightStateAmber;
boolean lightStateGreen;
private TrafficLight northLeftStraight;
private FourLightTrafficLight northLeftArrow;
private FourLightTrafficLight northRightArrow;
private TrafficLight eastLeftStraight;
private TrafficLight westStraightRight;
private FourWayJunction junction = new FourWayJunction();
#Before
public void createLights() throws Exception {
greenLight = (new Light(Shape.CIRCLE, Colour.GREEN));
amberLight = (new Light(Shape.CIRCLE, Colour.AMBER));
redLight = (new Light(Shape.CIRCLE, Colour.RED));
northRightArrow = new FourLightTrafficLight();
northLeftArrow = new FourLightTrafficLight();
northLeftStraight = new TrafficLight();
eastLeftStraight = new TrafficLight();
westStraightRight = new TrafficLight();
}
#Test
public void PhaseOneInitiation() throws Exception {
createLights();
//Greenleftarrow should be on, northleft on, and eat left on. All others off.
junction.initiatePhaseOne();
assertEquals(greenLeftArrow.isOn(), true);
}
}
This is the code containing the methods:
package com.nsa.y1.trafficlights;
/**
* Created by on 13/03/2017.
*/
public class FourWayJunction extends FourLightTrafficLight{
// Evans junction recreation in cardiff
private Light greenLight, amberLight, redLight, greenRightArrow, greenLeftArrow;
private TrafficLight oppositeTrafficLight;
private FourLightTrafficLight turnRightTrafficLight;
boolean lightStateRed;
boolean lightStateAmber;
boolean lightStateGreen;
private TrafficLight northLeftStraight;
private FourLightTrafficLight northLeftArrow;
private FourLightTrafficLight northRightArrow;
private TrafficLight eastLeftStraight;
private TrafficLight westStraightRight;
public FourWayJunction() {
greenLight = (new Light(Shape.CIRCLE, Colour.GREEN));
amberLight = (new Light(Shape.CIRCLE, Colour.AMBER));
redLight = (new Light(Shape.CIRCLE, Colour.RED));
northRightArrow = new FourLightTrafficLight();
northLeftArrow = new FourLightTrafficLight();
northLeftStraight = new TrafficLight();
eastLeftStraight = new TrafficLight();
westStraightRight = new TrafficLight();
}
public void initiatePhaseOne() {
// Left arrow for buses and taxis on, north green light for left on but no right arrow.
// Also green light on for the East Traffic light.
// All others off.
westStraightRight.getRedLight().turnOn();
northRightArrow.getGreenLight().turnOff();
if (westStraightRight.getRedLight().isOn() && !northRightArrow.getGreenLight().isOn()){
northLeftArrow.getGreenLight().turnOn();
northLeftStraight.setTrafficLightOn(northLeftStraight);
eastLeftStraight.setTrafficLightOn(eastLeftStraight);
}
else {
System.out.println("Problems, traffic wil collide");
westStraightRight.setTrafficLightOff(westStraightRight);
northRightArrow.getGreenLight().turnOff();
}
}
public void initiatePhaseTwo() {
// North left straight, left arrow, and right arrow are on.
// West straight right light off.
// East Left Straight light is off.
if (!eastLeftStraight.getRedLight().isOn()) {
eastLeftStraight.setTrafficLightOff(eastLeftStraight);
northRightArrow.getGreenLight().turnOn();
}
else {
northRightArrow.getGreenLight().turnOn();
}
}
public void initiatePhaseThree() {
// All lights are off except for the EastStraightRight light.
if (northRightArrow.getGreenLight().isOn() && !northLeftStraight.getRedLight().isOn() &&
northLeftArrow.getGreenLight().isOn()) {
northRightArrow.getGreenLight().turnOff();
northLeftArrow.getGreenLight().turnOff();
northLeftStraight.setTrafficLightOff(northLeftStraight);
}
else {
eastLeftStraight.setTrafficLightOn(eastLeftStraight);
}
}
public FourLightTrafficLight getTrafficLight(FourLightTrafficLight light) {
return light;
}
}
public void setTrafficLightOn(TrafficLight trafficLight) {
trafficLight.getRedLight().turnOff();
LightPause();
trafficLight.getAmberLight().turnOn();
LightPause();
trafficLight.getGreenLight().turnOn();
}
public void setTrafficLightOff(TrafficLight trafficLight) {
trafficLight.getGreenLight().turnOff();
LightPause();
trafficLight.getGreenLight().turnOff();
trafficLight.getAmberLight().turnOn();
LightPause();
trafficLight.getRedLight().turnOn();
}
Thanks for your help :)
greenLeftArrow is not initialized to a value (it's automatically initialized to null) so calling greenLeftArrow.isOn() in the PhaseOneInitialization method will throw a NullPointerException.
You should initialize greenLeftArrow object first like you did for example greenLight. You cannot call methods on not initialized objects.
You can also use assertTrue or assertFalse to simplify your code.

Mocking javax.mail.message with jMock

Following is the code that I am trying to use for mocking the javax.mail.Message. The message instance is passed to another method call getContent(Message message) which returns String instance. The code for this method is also given below.
Calendar cal = Calendar.getInstance();
mockery.setImposteriser(ClassImposteriser.INSTANCE);
final Message[] messages;
List<Message> ms = new ArrayList<Message>();
ms.add(mockery.mock(Message.class, "m1"));
ms.add(mockery.mock(Message.class, "m3"));
messages = ms.toArray(new Message[10]);
mockery.checking(new Expectations() {
{
allowing(messages[0]).getContentType();
will(returnValue("text/plain"));
allowing(messages[1]).getContentType();
will(returnValue("html"));
}
});
String contentM1 = getPasswordResetJob().getContent(messages[0]);
assertEquals("text/plain", contentM1);
getContent() method code :
log.info("Message content type::" + message.getContentType());
if (message.getContentType().contains("text/plain;")
&& message.getContent() != null) {
content = message.getContent().toString();
} else {
content = getMultipartContent(message);
}
return content;
The test case fails with this message.
unexpected invocation: m1.getContent()
expectations:
allowed, already invoked 2 times: m1.getContentType(); returns "text/plain"
allowed, never invoked: m3.getContentType(); returns "html"
at org.jmock.internal.InvocationDispatcher.dispatch(InvocationDispatcher.java:56)
at org.jmock.Mockery.dispatch(Mockery.java:204)
at org.jmock.Mockery.access$000(Mockery.java:37)
at org.jmock.Mockery$MockObject.invoke(Mockery.java:246)
at org.jmock.internal.InvocationDiverter.invoke(InvocationDiverter.java:27)
at org.jmock.internal.ProxiedObjectIdentity.invoke(ProxiedObjectIdentity.java:36)
at org.jmock.lib.legacy.ClassImposteriser$4.invoke(ClassImposteriser.java:137)
at $javax.mail.Message$$EnhancerByCGLIB$$8abdf7fe.getContent(<generated>)
at com.abc.scheduler.AbstractSchedulerJob.getMultipartContent(AbstractSchedulerJob.java:222)
at com.abc.scheduler.AbstractSchedulerJob.getContent(AbstractSchedulerJob.java:151)
at com.abc.scheduler.PasswordResetJobTest.testCreateAlertList(PasswordResetJobTest.java:127)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at junit.framework.TestCase.runTest(TestCase.java:168)
at junit.framework.TestCase.runBare(TestCase.java:134)
at org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:69)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:79)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
It seems that you didn't define the expectation for m1.getContent()
if (message.getContentType().contains("text/plain;")
&& message.getContent() != null) {
content = message.getContent().toString();//message.getContent() is not defined

Basic JUNIT testing. I am getting java.lang.AssertionError

I am new to JUNIT testing but tried a lot to test the class UserProfileService. Please help or suggest possible errors I am doing:
#Path("/update")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response updateProfile(final PartyProfile partyProfile) {
final ProxyResponse response = new ProxyResponse();
try {
final boolean isUpdated = partyProfileDao.updateProfile(partyProfile);
if (isUpdated) {
LOGGER.info("update Request completed successfully");
setSuccessResponse(response, "Request completed successfully");
try{
final String trailId = partyProfileDao.fetchPartyTrial(partyProfile.getPartyId());
activityPush(trailId, partyProfile.getPartyId());
}catch(Exception ex){
ex.printStackTrace();
LOGGER.error("Exception while triggering segmentation++");
}
} else {
LOGGER.info("Unable to update profile");
setErrorResponse(response, "PRFUPDT500", "Unable to update profile");
return Response.ok(response).header("valid", FLAG_FALSE).build();
}
} catch (Exception exc) {
LOGGER.error("Unable to update profile:" + exc.getMessage());
setInternalErrorResponse(exc, response, "Unable to update profile");
return Response.ok(response).header("valid", FLAG_FALSE).build();
}
return Response.ok(response).build();
}
I have written following JUNIT test:
public class PartyProfileServiceTest {
private PartyProfileDAO partyDAO;
private PartyProfileService partyService;
#Before
public void setUp() throws Exception {
partyDAO = EasyMock.createMock(PartyProfileDAO.class);
partyService = EasyMock.createMock(PartyProfileService.class);
partyService.setUserProfileDAO(partyDAO);
}
#Test
public void testUpdateValidProfile() throws Exception {
System.out.println("inside junit");
PartyProfile partyProfile = new PartyProfile();
partyProfile.setFirstName("adsfsdfg");
partyProfile.setAddress("adressabc");
partyProfile.setPartyId("dfdf");
partyProfile.getSalutation();
partyProfile.setMiddleName("asfsaf");
partyProfile.setLastName("easdsddff");
partyProfile.setNickName("srb");
partyProfile.setGender("m");
partyProfile.setUpdateDate("sdd");
partyProfile.setEducation("srg");
partyProfile.setInsurance("sg");
partyProfile.setState("sdfg");
partyProfile.setSiteId("fdg");
partyProfile.setRandomNo("feddg");
partyProfile.setPartyId("56666");
EasyMock.expect(partyDAO.updateProfile(partyProfile)).andReturn(true);
EasyMock.expect(partyDAO.fetchPartyTrial("validPartyId")).andReturn("pass");
EasyMock.replay(partyDAO);
EasyMock.expect(partyService.activityPush("pass", "validPartyId")).andReturn(true);
EasyMock.replay(partyService);
Response response = partyService.updateProfile(partyProfile);
ProxyResponse proxyResponse = (ProxyResponse) response.getEntity();
Assert.assertSame("Unable to update profile", proxyResponse.getData().get("message"));
}
}
Error:
java.lang.AssertionError:
Unexpected method call PartyProfileService.updateProfile(com.cts.vcoach.proxy.model.PartyProfile#11e170c):
PartyProfileService.setUserProfileDAO(EasyMock for class com.cts.vcoach.proxy.dao.PartyProfileDAO): expected: 1, actual: 0
PartyProfileService.activityPush("pass", "validPartyId"): expected: 1, actual: 0
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:97)
at com.cts.vcoach.proxy.service.rest.PartyProfileService$$EnhancerByCGLIB$$46a1112f.updateProfile(<generated>)
at com.cts.vcoach.proxy.service.rest.PartyProfileServiceTest.testUpdateValidProfile(PartyProfileServiceTest.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:44)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
You're trying to test the class PartyProfileService. So you should create an instance of this class, and call its methods in your test. But that's not what you're doing. You're creating a mock instance of this class:
partyService = EasyMock.createMock(PartyProfileService.class);
Replace this line by
partyService = new PartyProfileService();
If you need to partially mock the service, i.e. mock the method activityPush(), but not the other ethods, then see the documentation for how to do that:
ToMock mock = createMockBuilder(ToMock.class)
.addMockedMethod("mockedMethod")
.createMock();

Calling a method in another class causes NullPointerException

I am new to Java so please bear with me. I am using Java and Selenium to test a web application.
Basically, what I am trying to do is read in data from a cvs file in Class Main and then once I have the data, calling the login method in another class passing through the username and password variables read from the cvs file.
Maybe I am calling the function incorrectly, I am not sure but the line I get the NPE on is
driver.findElement(By.name("j_username")).clear();
in the Login function in the LiveProcess Class. If I move the Login method into the Main class I do not have any problems. I would appreciate any help you can give me - thanks in advance!
Main Class
public void ReadTestData() throws Exception
{
//Open CVS File and extract the contents
try {
CsvReader testData = new CsvReader("C:\\Selenium\\TestData.csv");
testData.readHeaders();
while (testData.readRecord())
{
String testType = testData.get("TestType");
String testName = testData.get("TestName");
String testDescription = testData.get("Description");
String userName = testData.get("UserName");
String password = testData.get("Password");
String firstName = testData.get("FirstName");
String lastName = testData.get("LastName");
int testTypeInt = Integer.parseInt(testType);
RunTests();
}
testData.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void RunTests() throws Exception
{
switch(testTypeInt)
{
case 1:
LiveProcessTests method = new LiveProcessTests();
method.Login(userName, password);
break;
default:
break;
}
}
LiveProcess Class
public void Login(String uName, String pWord) throws Exception
{
System.out.println("USER NAME: " + uName);
System.out.println("USER NAME: " + pWord);
driver.findElement(By.name("j_username")).clear();
driver.findElement(By.name("j_username")).click();
driver.findElement(By.name("j_username")).sendKeys(uName);
}
Actual Error:
java.lang.NullPointerException
at com.testscripts.LiveProcessTests.Login(LiveProcessTests.java:31)
at com.testscripts.Main.RunTests(Main.java:97)
at com.testscripts.Main.ReadTestData(Main.java:75)
at com.testscripts.Main.InitializeTests(Main.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Most likely driver.findElement(By.name("j_username")) is null which means it is unable to find the element you are searching.
Make sure the name is correct and that the element exist. Also You have to initialise the driver but it is not seen in your code
Example:
if (driver.findElement(By.name("j_username")) != null ) {
driver.findElement(By.name("j_username")).clear();
driver.findElement(By.name("j_username")).click();
driver.findElement(By.name("j_username")).sendKeys(uName);
}
UPDATE:
You should initialize your driver. Something like:
driver = new FirefoxDriver();

Categories