I'm using the newest versions of junit and jmockit and Oracle JDK 7 in Eclipse. When I try to mock java.net.URL my test won't run.
I have in my code something like:
URL url = new URL("String representing the url.");
So I figured in my test I could mock this like so:
#Mocked private URL _url;
Since this works for pretty much everything else, I know URL is final but I thought that was okay with JMockit.
When I run a test class with the above mock in eclipse the result is a grey line(as opposed to green or red.) So I'm assuming some kind of initialization problem. The rest of the test or code doesn't seem to matter, no matter what I put that #Mocked line in, this happens.
A workaround would be great, an explanation of what is actually causing this would be even better. Any help is definitely appreciated! Thanks!
Quick example. This actually gives an exception, but I think it is basically doing the same thing I have seen:
package demo;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Connecting {
public boolean connectionattempt() throws IOException {
URL url = new URL("http://nowhere/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection != null) {
return true;
}
else {
return false;
}
}
}
And this test:
package demo;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.Test;
import mockit.Expectations;
import mockit.Mocked;
import mockit.Tested;
public class TestConnecting {
#Mocked URL _url;
#Mocked HttpURLConnection _connection;
#Tested Connecting _sut;
#Test
public void testConnect() throws IOException {
new Expectations() { {
_url.openConnection(); result = _connection;
} };
assertEquals(true, _sut.connectionattempt());
}
}
and the stack trace:
java.lang.NoClassDefFoundError: org/eclipse/jdt/internal/junit/runner/TestReferenceFailure
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestListener.testFailure(JUnit4TestListener.java:91)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestListener.testFailure(JUnit4TestListener.java:69)
at org.junit.runner.notification.RunNotifier$4.notifyListener(RunNotifier.java:139)
at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:61)
at org.junit.runner.notification.RunNotifier.fireTestFailures(RunNotifier.java:134)
at org.junit.runner.notification.RunNotifier.fireTestFailure(RunNotifier.java:128)
at org.junit.internal.runners.model.EachTestNotifier.addFailure(EachTestNotifier.java:23)
at org.junit.runners.ParentRunner.run(ParentRunner.java:315)
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: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)
I executed the test on Eclipse Kepler SR2, IntelliJ IDEA 13.1, and Netbeans 8.0.1, using JMockit 1.13, JUnit 4.11, and Oracle JDK 1.7.0_67.
The test passes in every case, it's all green! So, I don't know what could possibly be the problem in your environment. Are you sure the "newest version" of JMockit (1.13 at this time) was the one actually used?
Related
I'm attempting to create unit tests for a JenkinsShared library using Gradle in order to run the test tasks.
I've followed this tutorial which upon conclusion one has a working test suite for a shared library for functions within the vars folder (with the unit tests in src/test/groovy/*Test.groovy).
However, in our internal shared jenkins library we followed a more object oriented style and isolated functionality into a package of classes in the format: src/org/company/*.groovy.
The problem arises when attempting to import said package into a unit test class. In the tutorial, the functions are imported using the loadScript method this method fails when loading a class which is dependent on another file.
Take the class:
package tests
import org.junit.*
import com.lesfurets.jenkins.unit.*
import static groovy.test.GroovyAssert.*
import org.company.UtilFactory
class UtilFactoryTest extends BasePipelineTest {
#Test
void testCall() {
def util = UtilFactory.getUtil("hello")
assertEquals true, true
}
}
src/org/company/UtilFactory.groovy
package org.company
class UtilFactory implements Serializable {
static Util instance
static Util getUtil(script=null) {
if (!(UtilFactory.instance)) {
if (!script) {
// Throws an exception if on the first call to getUtil the
// script parameter is null.
throw new ScriptUndefinedException("script parameter null on initial call to getUtil")
}
UtilFactory.instance = new Util(script)
}
return UtilFactory.instance
}
}
class ScriptUndefinedException extends Exception {
// Parameterless Constructor
public ScriptUndefinedException() {}
// Constructor that accepts a message
public ScriptUndefinedException(String message)
{
super(message);
}
}
Which gives me the exception:
jenkins-utilities/src/test/groovy/UtilFactoryTest.groovy: 7:
unable to resolve class org.company.UtilFactory
# line 7, column 1.
import org.company.UtilFactory
This may be more of a Gradle issue than a JenkinsShared Library. I've just spent a good portion of my day trying to figure out exactly what I'm doing wrong to no avail.
I would really appreciate any help to guide me in the right direction.
This library may be helpful getting your shared libraries to work in the unit test https://github.com/stchar/pipeline-sharedlib-testharness
We are running Struts 2.5.14.1 and working on externalizing Tomcat session state. This requires Serializable sessions. However, our Action with the ExecuteAndWait interceptor fails. Since our original code was quite complex I wrote a simpler one below which demonstrates the exact same behavior.
The simple action is shown here:
package com.sentrylink.web.actions;
import java.util.concurrent.TimeUnit;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.opensymphony.xwork2.ActionSupport;
#SuppressWarnings("serial")
#Results({
#Result(name="wait", location="/"),
#Result(name=ActionSupport.SUCCESS, location="/WEB-INF/content/messagePage.jsp"),
})
#InterceptorRefs({
#InterceptorRef("webStack"),
#InterceptorRef("execAndWait")
})
public class TestExecuteAndWait extends ActionSupport {
public String execute() throws Exception {
TimeUnit.SECONDS.sleep(10);
return SUCCESS;
}
}
Running this gives
WARNING: Cannot serialize session attribute __execWaittest-execute-and-wait for session 74CDB9F8D00BBC697030AFC6978E94F6
java.io.NotSerializableException: com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector
It appears that Struts is pulling in an unwanted item for serialization. It may be related to the bug described here, although the fix put in for that bug appears to be present in 2.5.14.1 (not surprisingly, since that fix was in 2013).
I suspect this is a bug in the framework, but before I go ahead and file a report, and figure out a workaround for myself, I thought I would see if anyone had a solution or had ever gotten ExecuteAndWait to work with serialized sessions.
i am new to Appium. I want to perform mobile testing on android and i OS app using appium tool on sauce labs.
I want to know what are the pre-requisites, and how to write the scripts(in java) and how exactly the flow goes.
can anybody help me out??
Thanks a lot in advance.. :-)
package com.saucelabs;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;
import static junit.framework.Assert.assertEquals;
/**
* Simple {#link RemoteWebDriver} test that demonstrates how to run your Selenium tests with Sauce OnDemand.
* *
* #author Ross Rowe
*/
public class DemoScript {
private WebDriver driver;
#Before
public void setUp() throws Exception {
DesiredCapabilities caps = DesiredCapabilities.android();
caps.setCapability("browserName", "");
caps.setCapability("platformVersion", "4.4");
caps.setCapability("appiumVersion", "");
caps.setCapability("platformName", "Android");
caps.setCapability("deviceName", "Android Emulator");
caps.setCapability("device-orientation", "portrait");
/* DesiredCapabilities capabillities = DesiredCapabilities.iphone();
capabillities.setCapability("version", "5.0");
capabillities.setCapability("platform", Platform.MAC);*/
this.driver = new RemoteWebDriver(
new URL("http://**********************"),caps);
}
#Test
public void basic() throws Exception {
driver.get("http://www.amazon.com/");
assertEquals("Amazon.com: Online Shopping for Electronics, Apparel, Computers, Books, DVDs & more", driver.getTitle());
}
#After
public void tearDown() throws Exception {
driver.quit();
}
}
i am new to Appium. I want to perform mobile testing on android and i OS app using appium tool on sauce labs.
I want to know what are the pre-requisites, and how to write the scripts(in java) and how exactly the flow goes.
can anybody help me out??
Thanks a lot in advance.. :-)
Are there any changes required in the code?
Is appium server should be started before running the script?
Answer 1 to this StackOverflow post provides some Groovy code, but it doesn't compile (for me, Groovy Console Version 2.1.3, or in my Grails 2.2.3 app).
Can you please assist in letting me know what I need to change to make this code work? The error I get is:
unexpected token: public at line 14, column: 52 (... which is the "public X509 Certificate[]")
For quick reference the code solution provided in Answer 1 is:
import javax.net.ssl.X509TrustManager
import javax.net.ssl.SSLContext
import java.security.cert.X509Certificate
import javax.net.ssl.TrustManager
import java.security.SecureRandom
import org.apache.http.conn.ssl.SSLSocketFactory
import org.apache.http.conn.scheme.Scheme
import org.apache.http.conn.scheme.SchemeRegistry
def http = new HTTPBuilder( "https://your_unsecure_certificate_host" )
//=== SSL UNSECURE CERTIFICATE ===
def sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, [ new X509TrustManager() {public X509Certificate[]
getAcceptedIssuers() {null }
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
} ] as TrustManager[], new SecureRandom())
def sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
def httpsScheme = new Scheme("https", sf, 443)
http.client.connectionManager.schemeRegistry.register( httpsScheme )
//================================
You probably have a newline between the public X509Certificate[] and getAcceptedIssuers() {null} as a result of pasting the code in.
Try removing the newline (and formatting the code to something moderately readable while you're at it) and the error should disappear.
So I am working on an app and I am getting a "packages cannot be nested" error when I try to run. There are no errors in the syntax that flash told me.
Code -
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class main extends MovieClip {
public function main() {
init()
}
private function init():void
{
home_button.addEventListener(MouseEvent.CLICK, handleButtonClicks);
}
private function handleButtonClicks():void
{
stop();
gotoAndStop("home_page");
}
}
}
Thanks
Old thread (month ago), i know.
I guess your code is in de fla (not an external as file).
Simply remove the word Package and it parenthesis (package {}) and run again.
This will work, guaranteed.
And also it is possible that flash gives an error about scope declarations like 'public', 'private' etc, remove also these.