Error when decrypt with Java - java

I'm having trouble when Iḿ trying to decrypt a document, I'm using Public/Private pair key to do this. I'm using a Token to do this.
This is the error that I'm getting:
java.security.ProviderException: java.security.KeyException: An internal error occurred.
at sun.security.mscapi.RSACipher.doFinal(RSACipher.java:297)
at sun.security.mscapi.RSACipher.engineDoFinal(RSACipher.java:321)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at org.bouncycastle.operator.jcajce.JceAsymmetricKeyUnwrapper.generateUnwrappedKey(Unknown Source)
at org.bouncycastle.cms.jcajce.JceKeyTransRecipient.extractSecretKey(Unknown Source)
at org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient.getRecipientOperator(Unknown Source)
at org.bouncycastle.cms.KeyTransRecipientInformation.getRecipientOperator(Unknown Source)
at org.bouncycastle.cms.RecipientInformation.getContentStream(Unknown Source)
at org.bouncycastle.cms.RecipientInformation.getContent(Unknown Source)
at ec.gov.informatica.firmadigital.cms.CMSEncryption.decrypt(CMSEncryption.java:198)
at ec.mil.gestordocumental.security.test.encryption.DecryptFileWithPublicCertificateToken.mainTest(DecryptFileWithPublicCertificateToken.java:110)
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: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.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
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)
Caused by: java.security.KeyException: An internal error occurred.
at sun.security.mscapi.RSACipher.encryptDecrypt(Native Method)
at sun.security.mscapi.RSACipher.doFinal(RSACipher.java:289)
... 32
And this is the code I'm using to decrypt:
public static byte[] decrypt(byte[] encrypted, X509Certificate cert, PrivateKey privateKey, Provider provider) {
try {
CMSEnvelopedData enveloped = new CMSEnvelopedData(encrypted);
RecipientInformationStore recipients = enveloped.getRecipientInfos();
X509CollectionStoreParameters s = new X509CollectionStoreParameters(Collections.singleton(new JcaX509CertificateHolder(cert)));
X509StoreCertCollection s1 = new X509StoreCertCollection();
s1.engineInit(s);
Iterator it = recipients.getRecipients().iterator();
RecipientInformation recipient = null;
while (it.hasNext()) {
recipient = (RecipientInformation) it.next();
if (recipient instanceof KeyTransRecipientInformation) {
Collection matches = s1.engineGetMatches(recipient.getRID());
if (!matches.isEmpty()) {
JceKeyTransEnvelopedRecipient ter = null;
if ("sun.security.mscapi.RSAPrivateKey".equals(privateKey.getClass().getCanonicalName() ) ) {
ter = new JceKeyTransEnvelopedRecipient(privateKey);
ter.setProvider( "SunMSCAPI" );
ter.setContentProvider(BouncyCastleProvider.PROVIDER_NAME);
} else {
ter = new JceKeyTransEnvelopedRecipient(privateKey);
ter.setProvider(BouncyCastleProvider.PROVIDER_NAME);
}
return recipient.getContent(ter);
}
} else {
throw new RuntimeException("Wrong type of RecipientInformation: " + recipient.getClass());
}
recipient=null;
}
if (recipient == null) {
throw new RuntimeException("Could not find a matching recipient");
}
} catch (CMSException e) {
throw new RuntimeException(e); // FIXME
} catch (CertificateEncodingException e) {
throw new RuntimeException(e);
}
}
Please help me what it could be.
Thanks a lot.

I'm having the same problem for decryption, using both MSCAPI and PKCS#11. I found that the P11RSAChiper implemented in SunPKCS11 doesn't regard the wrap/unwrap methods, and it uses encrypt/decrypt for this purpose, which in my case conflicts with underlying layer of security, where the private key is marked just for unwrap by the SmartCard profile.

Related

EasyMock unexpected method call

I can't work out how to setup the expectation of a call to a mock class. Here is the JUnit test:
public class AfkTest extends TestCase {
private AfkPlayerManager manager;
private Player player;
private Set<AfkPlayer> afkPlayers;
public void setUp() throws Exception {
super.setUp();
manager = new AfkPlayerManager();
player = EasyMock.createMock(Player.class);
afkPlayers = new HashSet<AfkPlayer>();
}
public void tearDown() {
}
public void testNotifyOfAfkPlayerSuccess() {
AfkPlayer afkPlayer = new AfkPlayer();
afkPlayer.setPlayer(player);
afkPlayer.setReason("TEST REASON");
afkPlayers.add(afkPlayer);
List<Player> onlinePlayers = new ArrayList<Player>();
onlinePlayers.add(player);
onlinePlayers.add(player);
EasyMock.expect(player.getDisplayName()).andReturn("TEST PLAYER");
player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]");
EasyMock.expectLastCall().times(1);
//activate the mock
EasyMock.replay(player);
assertTrue(manager.notifyOfAfkPlayer(onlinePlayers, afkPlayer));
//verify call to sendMessage is made or not
EasyMock.verify(player);
}
}
And the method that I am testing:
public class AfkPlayerManager implements Manager {
public boolean notifyOfAfkPlayer(Collection<Player> onlinePlayers, AfkPlayer afkPlayer) {
if (afkPlayer == null) {
return false;
}
String message = ChatColor.BLUE + afkPlayer.getPlayer().getDisplayName();
message += ChatColor.AQUA + " is AFK.";
if (afkPlayer.getReason().length() > 0) {
message += " [" + afkPlayer.getReason() + "]";
}
if (onlinePlayers != null && onlinePlayers.size() > 1) {
int notified = 0;
for (Player onlinePlayer : onlinePlayers) {
onlinePlayer.sendMessage(message);
notified++;
}
if (notified > 0) {
return true;
}
}
return false;
}
}
Why is this giving me the AssertionError:
java.lang.AssertionError: Unexpected method call
Player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]"):
Player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]"): expected: 1, actual: 0 at
org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at
org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
at com.sun.proxy.$Proxy3.sendMessage(Unknown Source) at
crm.afk.AfkPlayerManager.notifyOfAfkPlayer(AfkPlayerManager.java:33)
at crm.test.AfkTest.testNotifyOfAfkPlayerSuccess(AfkTest.java:84) 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)
The expected and actual are different.
Expected: §9TEST PLAYER§b is AFK. [TEST REASON]
Actual: §9TEST PLAYER§b is AFK. [TEST REASON]
The  at the beginning is missing. So it fails as it should.

Why does dom4j throw InvalidXPathException for a valid XPath only in my test environment?

I'm working on authoring some unit testing for some code that I've got working in a system, but I'm having problems with InvalidXPathException's being thrown on valid XPaths.
Using //external|//inline to extract out certain elements out of a DOM4J document, and it works in production but not in my test environment. There shouldn't be an issue as it's a valid XPath that I've tested outside of the environment.
Any help would be appreciated!
jUnit/Easymock test:
#Test
public void testgetDCR_success(){
RequestContext context = EasyMock.createMock(RequestContext.class);
FileDal dal = EasyMock.createMock(FileDal.class);
String xmlContent = "<xml>your sample stuff</xml>";
Document sampleDoc = Dom4jUtils.newDocument(xmlContent);
InputStream stream = null;
try {
stream = new ByteArrayInputStream(xmlContent.getBytes("UTF-8"));
} catch(IOException e) {
Assert.fail("Could not open file stream for test.");
}
EasyMock.expect(context.getFileDal()).andReturn(dal).anyTimes();
EasyMock.expect(dal.getRoot()).andReturn("").anyTimes();
EasyMock.expect(dal.getSeparator()).andReturn('/').anyTimes();
EasyMock.expect(dal.exists("/some/path")).andReturn(true);
EasyMock.expect(dal.read("/some/path")).andReturn(xmlContent);
EasyMock.expect(dal.getStream("some/path")).andReturn(stream);
EasyMock.replay(context);
EasyMock.replay(dal);
Document doc = new DefaultTransformationService().getDCR(context, "some/path");
Assert.assertEquals(sampleDoc, doc);
}
Lead up to the issue:
#Override
public Document getDCR(RequestContext context, String relativePath) {
LOGGER.debug(">> getDCR");
if (StringUtils.isBlank(relativePath)) {
LOGGER.error("No origin file path given");
LOGGER.debug("<< getDCR");
return null;
}
Document dcrDoc = null;
try {
dcrDoc = ExternalUtils.readXmlFile(context, relativePath);
}catch (RuntimeException e){
LOGGER.error("No DCR found at file path: "+relativePath,e);
LOGGER.debug("<< getDCR");
return null;
}
if (dcrDoc == null) {
LOGGER.error("Unable to open xml file: " + relativePath);
LOGGER.debug("<< getDCR");
return null;
}
LOGGER.debug("<< getDCR");
Set<String> parsedPaths = new HashSet<String>();
parsedPaths.add(relativePath);
return parseData(context, dcrDoc, parsedPaths);
}
private Document parseData(RequestContext context, Document dcr, Set<String> parsedPaths) {
LOGGER.debug(">> parseData");
// get all nodes that would be converted.
#SuppressWarnings("unchecked")
List<Element> elements = dcr.selectNodes("//external|//inline");
// For each of the nodes present within the document that are of type external or inline
for (Element element : elements) {
// process each element in the list of selected elements.
processElement(context, element, parsedPaths);
}
LOGGER.debug("<< parseData");
return dcr;
}
Stack trace:
org.dom4j.InvalidXPathException: Invalid XPath expression: '//external|//inline'. Caused by: org/jaxen/dom4j/Dom4jXPath
at org.dom4j.xpath.DefaultXPath.parse(DefaultXPath.java:362)
at org.dom4j.xpath.DefaultXPath.<init>(DefaultXPath.java:59)
at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207)
at org.dom4j.tree.AbstractNode.selectNodes(AbstractNode.java:164)
at com.sample.project.service.impl.DefaultTransformationService.parseData(DefaultTransformationService.java:163)
at com.sample.project.service.impl.DefaultTransformationService.getDCR(DefaultTransformationService.java:144)
at com.sample.project.service.impl.DefaultTransformationServiceTest.testgetDCR_success(DefaultTransformationServiceTest.java:84)
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: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.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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Looking at the DOM4J source code, one can see that the root cause for that exception is not necessarily an invalid XPath expression:
protected static XPath parse(String text) {
try {
return new Dom4jXPath(text);
} catch (JaxenException e) {
throw new InvalidXPathException(text, e.getMessage());
} catch (Throwable t) {
throw new InvalidXPathException(text, t);
}
}
And given how the message looks, one can conclude that Throwable was catched. From InvalidXPathException:
public InvalidXPathException(String xpath, Throwable t) {
super("Invalid XPath expression: '" + xpath
+ "'. Caused by: " + t.getMessage());
}
Unfortunately, DOM4J hides the original exception in this case, but
Caused by: org/jaxen/dom4j/Dom4jXPath
implies that the original exception is a NoClassDefFoundError.
However, it is strange that that Dom4jXPath cannot be found while JaxenException is obviously found (since they live in the same jar (jaxen)). Anyway, it looks like your classpath is not set up properly.
BTW, the preceding "analysis" is based on DOM4J 1.6.1., so if you use another version YMMV.

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