How to work with junit ExpectedException? - java

I'm trying to work with ExpectedExceptions for JUnit. I tried already this:
public class ExpectedTest {
#Rule
public ExpectedException thrown = ExpectedException.none();
#Test
public void test() {
thrown.expect(NullPointerException.class);
throw new NullPointerException();
}
}
which raises me the following Exception:
java.lang.NoClassDefFoundError: org/hamcrest/TypeSafeMatcher at
java.lang.ClassLoader.defineClass1(Native Method) at
java.lang.ClassLoader.defineClass(ClassLoader.java:800) at
java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at
java.net.URLClassLoader.access$100(URLClassLoader.java:71) at
java.net.URLClassLoader$1.run(URLClassLoader.java:361) at
java.net.URLClassLoader$1.run(URLClassLoader.java:355) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:354) at
java.lang.ClassLoader.loadClass(ClassLoader.java:425) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at
java.lang.ClassLoader.loadClass(ClassLoader.java:358) at
org.junit.matchers.JUnitMatchers.isThrowable(JUnitMatchers.java:103)
at
org.junit.rules.ExpectedExceptionMatcherBuilder.build(ExpectedExceptionMatcherBuilder.java:27)
at
org.junit.rules.ExpectedException.handleException(ExpectedException.java:198)
at
org.junit.rules.ExpectedException.access$500(ExpectedException.java:85)
at
org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:177)
at org.junit.rules.RunRules.evaluate(RunRules.java:20) 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: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.lang.ClassNotFoundException:
org.hamcrest.TypeSafeMatcher at
java.net.URLClassLoader$1.run(URLClassLoader.java:366) at
java.net.URLClassLoader$1.run(URLClassLoader.java:355) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:354) at
java.lang.ClassLoader.loadClass(ClassLoader.java:425) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at
java.lang.ClassLoader.loadClass(ClassLoader.java:358) ... 33 more
When I do it like this:
public class ExpectedTest {
#Rule
public ExpectedException thrown;
#Before
public void setup() {
thrown = ExpectedException.none();
}
#Test
public void test() {
thrown.expect(NullPointerException.class);
throw new NullPointerException();
}
}
I get a simple NullPointerException! What am I doing wrong?

java.lang.NoClassDefFoundError: org/hamcrest/TypeSafeMatcher suggests that you should make sure that hamcrest-core is on the runtime classpath, or add it if it's missing

You need following dependency
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>

Try this in the test that is supposed to throw the exception:
#Test(expected = NullPointerException.class)

Related

How to test Servlet on Mockito?

I'm new to mokito, I'm trying to test my servlet who is responsible for registering the user. I'm trying to lock up the HttpRequestServlet but I always get ClassFormException. I can not understand why. How can this be fixed, can you tell? How it is possible to properly test a servlet and to mock HttpServletRequest?
#Mock
private HttpServletRequest request = mock(HttpServletRequest.class); ;
#After
public void verifyRequest(){
verify(request).getParameter(ConstantApp.RegistrationConstantField.GET_FIRST_NAME);
verify(request).getParameter(ConstantApp.RegistrationConstantField.GET_LAST_NAME);
verify(request).getParameter(ConstantApp.RegistrationConstantField.GET_LOGIN);
verify(request).getParameter(ConstantApp.RegistrationConstantField.GET_EMAIL);
verify(request, Mockito.atLeast(2)).getParameter(ConstantApp.RegistrationConstantField.GET_PASSWORD);
verify(request).getParameter(ConstantApp.RegistrationConstantField.GET_CONFIRM_PASSWORD);
}
#Test
public void shouldReturnTrue_WhenWeGetValidField() throws Exception{
when(request.getParameter(ConstantApp.RegistrationConstantField.GET_FIRST_NAME)).thenReturn("Aloha");
when(request.getParameter(ConstantApp.RegistrationConstantField.GET_LAST_NAME)).thenReturn("Dance");
when(request.getParameter(ConstantApp.RegistrationConstantField.GET_LOGIN)).thenReturn("AlohaDance123");
when(request.getParameter(ConstantApp.RegistrationConstantField.GET_EMAIL)).thenReturn("aloha.dance#gmail.com");
when(request.getParameter(ConstantApp.RegistrationConstantField.GET_PASSWORD)).thenReturn("12345678Aa$");
when(request.getParameter(ConstantApp.RegistrationConstantField.GET_CONFIRM_PASSWORD)).thenReturn("12345678Aa$");
Validation validation = new Validation();
Map<String, String> errorMap = validation.validate(new RegistrationInfoImpl(request));
assertTrue(errorMap.isEmpty());
}
My Exception:
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/servlet/ServletException
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.getDeclaredMethods(Class.java:1975)
at org.mockito.cglib.core.ReflectUtils.addAllMethods(ReflectUtils.java:349)
at org.mockito.cglib.proxy.Enhancer.getMethods(Enhancer.java:427)
at org.mockito.cglib.proxy.Enhancer.generateClass(Enhancer.java:457)
at org.mockito.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:217)
at org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
at org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318)
at org.mockito.internal.creation.cglib.ClassImposterizer.createProxyClass(ClassImposterizer.java:123)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:57)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:49)
at org.mockito.internal.creation.cglib.CglibMockMaker.createMock(CglibMockMaker.java:24)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
at org.mockito.Mockito.mock(Mockito.java:1285)
at org.mockito.Mockito.mock(Mockito.java:1163)
at servlet.RegistrationServletTest.<init>(RegistrationServletTest.java:25)

Connect to Test Hbase table via Phoenix

I wanted to know if and how can I connect to HBaseTestTable which I made using
(org.apache.hadoop.hbase.HBaseTestingUtility;) via Phoenix. I want to have a successful connection to Hbase then insert into the Test table and retrieve data from the Test table. I have been able to create a HbaseTable. But unable to connect to it via Phoenix. Also unable to use writeToPhoenix function.
I am sharing the code which I have written:
#BeforeClass
public static void init() throws Exception {
testingUtility = new HBaseTestingUtility();
testingUtility.startMiniCluster();
hbaseConfiguration = testingUtility.getHBaseCluster().getConfiguration();
String zkQuorum = "localhost:" + testingUtility.getZkCluster().getClientPort();
Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
java.sql.Connection connection = DriverManager.getConnection("jdbc:phoenix:"+zkQuorum);
connection.setAutoCommit(true);
try {
Statement statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE TEST(" +
"KEY VARCHAR NOT NULL," +
"VALUE1 VARCHAR NOT NULL," +
"VALUE2 VARCHAR NOT NULL," +
"CONSTRAINT PK PRIMARY KEY(KEY)" +
")");
connection.commit();
log.info("HBase table via Phoenix created successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
Stack Trace :
java.lang.ClassNotFoundException: org.apache.phoenix.jdbc.PhoenixDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:191)
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: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.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Thanks.
You need to add the Phoenix jar file to your classpath in IntelliJ

java.lang.ClassNotFoundException: org.junit.runners.BlockJUnit4ClassRunner

I have no problem executing this Junit (junit-4.4) of a spring 3.2.8 project from Eclipse, (Click right button -> Run As -> Junit Test)
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class AccomodationTypeDaoTest extends BaseDaoTest {
private AccomodationTypeDao accTypeDao;
#Test
public void testFindAll() {
assertNotNull(accTypeDao.findAll());
}
#Autowired
public void setAccomodationTypeDao(AccomodationTypeDao daoInstance) {
this.accTypeDao = daoInstance;
}
}
#SuppressWarnings("deprecation")
public class BaseDaoTest extends AbstractAnnotationAwareTransactionalTests {
private static final String[] CONFIG_LOCATIONS = new String[] { "classpath:com/dao/testDataAccessContext.xml" };
#Override
protected String[] getConfigLocations() {
return CONFIG_LOCATIONS;
}
#Test
public void testBaseDaoTest() {
assertTrue(true);
}
}
I have no problem as well, doing the same with all the classes form the package.
But when I click in the test folder /MyProject/MyProjectWeb/test/src I got this exception:
java.lang.TypeNotPresentException: Type [unknown] not present
at sun.reflect.annotation.TypeNotPresentExceptionProxy.generateException(TypeNotPresentExceptionProxy.java:46)
at sun.reflect.annotation.AnnotationInvocationHandler.invoke(AnnotationInvocationHandler.java:75)
at com.sun.proxy.$Proxy6.value(Unknown Source)
at org.junit.internal.requests.ClassRequest.getRunnerClass(ClassRequest.java:49)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:28)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:25)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
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.lang.NoClassDefFoundError: org/junit/runners/BlockJUnit4ClassRunner
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:270)
at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114)
at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125)
at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
at sun.reflect.annotation.AnnotationParser.parseSig(AnnotationParser.java:390)
at sun.reflect.annotation.AnnotationParser.parseClassValue(AnnotationParser.java:371)
at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:300)
at sun.reflect.annotation.AnnotationParser.parseAnnotation(AnnotationParser.java:241)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:88)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:70)
at java.lang.Class.initAnnotationsIfNecessary(Class.java:3217)
at java.lang.Class.initAnnotationsIfNecessary(Class.java:3224)
at java.lang.Class.initAnnotationsIfNecessary(Class.java:3224)
at java.lang.Class.getAnnotation(Class.java:3176)
at org.junit.internal.requests.ClassRequest.getRunnerClass(ClassRequest.java:45)
... 9 more
Caused by: java.lang.ClassNotFoundException: org.junit.runners.BlockJUnit4ClassRunner
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 37 more
From the javadoc of BlockJUnit4ClassRunner:
/**
* [...]
* </ul>
*
* #since 4.5
*/
public class BlockJUnit4ClassRunner
So it's not available in 4.4, you probably can upgrade to 4.11 without any code change

Cannot run Robolectric tests with Gradle and Android Studio - StyleData not found

I downloaded deckard-gradle project and I have created my own with this temple.
My problem is that Robolectric.2.3 does not want to run test for class.
This is my error:
java.lang.RuntimeException: huh? can't find parent for StyleData{name='AppTheme', parent='Theme_AppCompat_Light_DarkActionBar'}
at org.robolectric.shadows.ShadowAssetManager$StyleResolver.getParent(ShadowAssetManager.java:365)
at org.robolectric.shadows.ShadowAssetManager$StyleResolver.getAttrValue(ShadowAssetManager.java:350)
at org.robolectric.shadows.ShadowResources.findAttributeValue(ShadowResources.java:293)
at org.robolectric.shadows.ShadowResources.attrsToTypedArray(ShadowResources.java:196)
at org.robolectric.shadows.ShadowResources.access$000(ShadowResources.java:55)
at org.robolectric.shadows.ShadowResources$ShadowTheme.obtainStyledAttributes(ShadowResources.java:494)
at org.robolectric.shadows.ShadowResources$ShadowTheme.obtainStyledAttributes(ShadowResources.java:489)
at org.robolectric.shadows.ShadowResources$ShadowTheme.obtainStyledAttributes(ShadowResources.java:484)
at android.content.res.Resources$Theme.obtainStyledAttributes(Resources.java)
at android.content.Context.obtainStyledAttributes(Context.java:380)
at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:104)
at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:98)
at pl.grzeslowski.historia_miasta.activities.MainActivity_.onCreate(MainActivity_.java:31)
at android.app.Activity.performCreate(Activity.java:5133)
at org.fest.reflect.method.Invoker.invoke(Invoker.java:112)
at org.robolectric.util.ActivityController$1.run(ActivityController.java:147)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:265)
at org.robolectric.util.ActivityController.create(ActivityController.java:144)
at org.robolectric.util.ActivityController.create(ActivityController.java:154)
at pl.grzeslowski.historia_miasta.activities.MainActivityTest.testSomething(MainActivityTest.java:21)
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.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:250)
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.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:177)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:86)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:49)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:50)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.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:103)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355)
at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
I run into similar problem, RobolectricTestRunner can't find the Android library dependencies. To resolve this issue you need to extend from RobolectricTestRunner to pull them in.android-maven-plugin unpacks your APK dependencies depending on version of the plugin into "target/unpack/apklibs" or to "target/unpacked-libs". The example I pasted below resolve problem for second one.
public class MyTestRunner extends RobolectricTestRunner {
public MyTestRunner(Class<?> testClass) throws InitializationError {
super(testClass);
}
#Override
protected AndroidManifest createAppManifest(FsFile manifestFile, FsFile resDir, FsFile assetsDir) {
return new MavenAndroidManifest( manifestFile, resDir, assetsDir);
}
public static class MavenAndroidManifest extends AndroidManifest {
public MavenAndroidManifest(FsFile androidManifestFile, FsFile resDirectory, FsFile assetsDirectory) {
super(androidManifestFile, resDirectory, assetsDirectory);
}
public MavenAndroidManifest(FsFile libraryBaseDir) {
super(libraryBaseDir);
}
#Override
protected List<FsFile> findLibraries() {
// Change "target/unpacked-libs" to "target/unpack/apklibs"
//if youe have older version of android-maven-plugin
FsFile unpack = getBaseDir().join("target/unpacked-libs");
if (unpack.exists()) {
FsFile[] libs = unpack.listFiles();
if (libs != null) {
return Arrays.asList(libs);
}
}
return Collections.emptyList();
}
#Override
protected AndroidManifest createLibraryAndroidManifest(FsFile libraryBaseDir) {
return new MavenAndroidManifest(libraryBaseDir);
}
}
}
Later in test cases use it like this:
#RunWith(MyTestRunner.class)
#Config(emulateSdk = 18)
public class MyActivityTest{
}

JUnit testing Akka actors in play framework 2.0.4 - JAVA ClassNotFoundException on scala.concurrent.duration.Duration

I am trying to implement a JUnit test to test an actor.
I have this ActorTest :
import org.junit.Test;
import play.libs.Akka;
import playtests.PlayFrameworkTest;
import akka.actor.Actor;
import akka.actor.Props;
import akka.actor.UntypedActorFactory;
import akka.testkit.TestActorRef;
public class ActorTest {
public static FakeApplication dummy;
#BeforeClass
public static void startApp() {
dummy = Helpers.fakeApplication(Helpers.inMemoryDatabase());
Helpers.start(dummy);
}
#AfterClass
public static void stopApp() {
Helpers.stop(dummy);
}
#Test
public void test() throws Exception {
final String myParameter = "someParameter";
#SuppressWarnings("serial")
TestActorRef<MyActor> actorRef = TestActorRef.create(Akka.system(), new Props(new UntypedActorFactory() {
#Override
public Actor create() {
return new MyActor(myParameter);
}
}), "testActor");
MyActor actor = actorRef.underlyingActor();
String message = "message";
actor.apply(message);
actor.receive();
}
}
When I try to run it (both on eclipse and with 'play test' commandline) is I get this exception thrown at the line of the TestActorRef.create()
java.lang.NoClassDefFoundError: scala/concurrent/duration/Duration
at persistence.actors.ActorTest.test(ActorTest.java:45)
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:601)
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.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
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.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: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.lang.ClassNotFoundException: scala.concurrent.duration.Duration
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 26 more
I have looked http://doc.akka.io/docs/akka/snapshot/java/testing.html
and
http://doc.akka.io/docs/akka/snapshot/scala/testing.html
and all I could find on the play framework page.
What am I missing? Why is it not running? I get the same exception if I get my system from Akka.system() and ActorSystem.apply() ... same thing when I pass it my fakeApplication or not.
(To summarise the comments aboveā€¦) The class scala.concurrent.duration.Duration was first included with Scala 2.10. At the time of writing Akka 2.1 and Play 2.1 are the best releases to work with Scala 2.10.

Categories