#Rule declaration causes error on a debug attempt - java

A groovy JUnit test class has only one static declaration:
#Rule
public static ErrorCollector errorCollector;
After an attempt to launch the test in debug mode an exception raises:
java.lang.NullPointerException
at org.junit.runners.BlockJUnit4ClassRunner.withRules(BlockJUnit4ClassRunner.java:354)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:270)
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.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
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 exception raises before any line in the code is started.
If I throw away the "#Rule" word, the test is running OK (at least from the start)
Imports are:
import static org.hamcrest.CoreMatchers.*;
import org.hamcrest.Matcher;
import static org.hamcrest.Matchers.*;
import org.junit.Rule;
import org.junit.rules.ErrorCollector;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Before;
import groovy.util.slurpersupport.NodeChild
import groovy.xml.MarkupBuilder
import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil
import org.codehaus.groovy.tools.xml.DomToGroovy
import org.joda.time.DateTime
import org.w3c.dom.Document;
import java.util.concurrent.Callable;
JUnit version 4.8.2
Eclipse version: 3.6
Java version: 1.6.41
Where should I look for problems, please?

As you can see at ErrorCollector javadoc, you must create a instance to use it, like this:
#Rule
public ErrorCollector collector= new ErrorCollector();

It seems as a bug in Runner:
//Correct variants:
#Rule
public ErrorCollector collector1= new ErrorCollector();
public ErrorCollector collector2= null;
#Rule
collector2= new ErrorCollector();
public ErrorCollector collector3;
#Rule
collector3= new ErrorCollector();
// incorrect variants:
#Rule
public ErrorCollector collector4= null;
#Rule
public ErrorCollector collector5;
#Rule
public ErrorCollector collector5=somethingThatIsNotRule;
#Rule
public ErrorCollector collector5=anotherRule;
//BUT:
//the runner takes the following, and runs it without problems, too:
public ErrorCollector collector6= null;
{
#Rule
collector6= null;
}
So, the runner makes an excessive check before constructing the test.

Related

java.lang.AssertionError: Cassandra daemon did not start within timeout

My Test Class :
public class NetworkSettingsDaoTest {
#Rule
public CassandraCQLUnit cassandraCQLUnit = new CassandraCQLUnit(new ClassPathCQLDataSet("simpleWithCreateKeyspace.cql"));
public static Session session;
public static NetworkSettingsDao networkSettingsDao;
#Before
public void init() throws ConfigurationException, TTransportException, IOException, InterruptedException{
EmbeddedCassandraServerHelper.startEmbeddedCassandra(5600000L);
//Thread.sleep(4*1000); //workaround for weak machine
session = cassandraCQLUnit.getSession();
networkSettingsDao = new NetworkSettingsDao();
}
#Test
public void should_have_started_and_execute_cql_script() throws Exception {
ResultSet result = session.execute("select * from mytable WHERE id='myKey01'");
assertThat(result.iterator().next().getString("value"), is("myValue01"));
}
}
My simpleWithCreateKeyspace.cql file :
CREATE KEYSPACE NETWORKSETTINGS WITH replication={'class' : 'SimpleStrategy', 'replication_factor':1};
USE NETWORKSETTINGS;
CREATE TABLE STBDevice(
KEY varchar,
SETTINGS_COLUMN varchar,
AMSIP varchar,
PRIMARY KEY(KEY));
INSERT INTO STBDevice(KEY, SETTINGS_COLUMN,AMSIP) values('myKey01','myColumn1','myAMSIP1');
Exception :
java.lang.AssertionError: Cassandra daemon did not start within
timeout at
org.cassandraunit.utils.EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.java:130)
at
org.cassandraunit.utils.EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.java:85)
at
org.cassandraunit.utils.EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.java:64)
at
org.cassandraunit.utils.EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.java:56)
at
org.cassandraunit.BaseCassandraUnit.before(BaseCassandraUnit.java:28)
at
org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:46)
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: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)
In my case, the server ALWAYS started within the default 10 sec window until yesterday. Today, it takes 50 to 70 secs. No valid explanation. So, looks like the only option is to increase the timeout.
Looks, It depends on the number of queries you fire on Cassandra.. If you have too many queries to run then you need to increase the timeout in EmbeddedCassandra annotation. #EmbeddedCassandra(timeout = 100000L)
This class helped to solve problems
package org.cassandraunit.test.spring.cql;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import org.cassandraunit.spring.CassandraDataSet;
import org.cassandraunit.spring.CassandraUnitTestExecutionListener;
import org.cassandraunit.spring.EmbeddedCassandra;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
#RunWith(SpringJUnit4ClassRunner.class)
#TestExecutionListeners({ CassandraUnitTestExecutionListener.class })
#CassandraDataSet(value = { "simple.cql" })
#EmbeddedCassandra
public class SpringCQLScriptLoadTest {
#Test
public void should_have_started_and_execute_cql_script() throws Exception {
Cluster cluster = Cluster.builder()
.addContactPoints("127.0.0.1")
.withPort(9142)
.build();
Session session = cluster.connect("cassandra_unit_keyspace");
ResultSet result = session.execute("select * from mytable WHERE id='myKey01'");
assertThat(result.iterator().next().getString("value"), is("myValue01"));
}
}

Mockito/PowerMockito: Weird Stubbing Exception

I'm getting this org.mockito.exceptions.misusing.UnfinishedStubbingException but based on all posts and descriptions I could find at internet, it doesn't seem to make sense.
The exception method states a thenReturn may be missing, but it's not. I left on purpose both ways on my example code below: doReturn and thenReturn. None of them worked. Both with the very same exception message.
Also, there are no inline mocks. I prepared all static classes and am using PowerMockitoRunner.
I can't find any way out. Any one can help me find out what's going on?
Edit: I forgot to mention I'm using Mockito 1.8.5 and PowerMockito 1.4.10.
Full exception:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:31)
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. although stubbed methods may return mocks, you cannot inline mock creation (mock()) call inside a thenReturn method (see issue 53)
at br.com.tests.email.EnvioCompartilhamento.mockCaptcha(EnvioCompartilhamento.java:120)
at br.com.tests.email.EnvioCompartilhamento.setup(EnvioCompartilhamento.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:132)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:95)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:102)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
My test class. Code lines added 10 by 10 (or sort of):
006 --> import br.com.common.MyProperties;
import br.com.struts.email.EnvioDeEmail;
import br.com.struts.email.forms.FormularioParaCompartilhamento;
import br.com.util.UrlUtil;
010 --> import br.com.popular.commons.Publications;
import br.com.popular.commons.utils.escenic.RetrievingObjects;
import com.captcha.Captcha;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
020 --> import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import static org.junit.Assert.assertNull;
030 --> import static org.junit.Assert.fail;
import static org.mockito.Matchers.*;
import static org.powermock.api.mockito.PowerMockito.*;
040 --> #RunWith(PowerMockRunner.class)
#PrepareForTest({ Captcha.class, RetrievingObjects.class, UrlUtil.class })
public class EnvioCompartilhamento {
#Mock
private ActionMapping mapping;
#Mock
private HttpServletRequest request;
050 --> #Mock
private HttpServletResponse response;
private FormularioParaCompartilhamento formulario;
#Before
public void setup() throws NoSuchMethodException, NoSuchFieldException, IOException {
mockStaticClasses();
mockRequestBehavior();
060 --> mockCaptcha();
mockResponse();
formulario = new FormularioParaCompartilhamento();
}
#Test
public void compartilhamentoComSucesso() {
formulario.setEmailTo("teste#teste.com");
formulario.setIdArtigo("12345");
070 --> formulario.setIsArtigo(true);
formulario.setMessage("Corpo do email");
formulario.setTitulo("Titulo");
formulario.setUrl("http://www.google.com");
formulario.setCaptcha("ABCD");
EnvioDeEmail email = new EnvioDeEmail();
final ActionForward resultado = email.compartilhamento(mapping, formulario, request, response);
assertNull(resultado);
080 --> }
112 --> private void mockRequestBehavior() {
when(request.getMethod()).thenReturn("POST");
when(request.getHeader("X-FORWARDED-FOR")).thenReturn("User IP");
}
private void mockCaptcha() {
120 --> HttpSession session = mock(HttpSession.class);
doReturn(session).when(request).getSession();
Captcha captcha = Mockito.mock(Captcha.class);
doReturn(captcha).when(session).getAttribute("captcha");
doReturn(true).when(captcha).isInputValid(anyString());
}
private void mockStaticClasses() {
final MyProperties myProperties = mock(MyProperties.class);
130 --> mockStatic(RetrievingObjects.class);
when(RetrievingObjects.componentFromPublicationAtSystemScope(any(Publications.class), eq("EmailProperties"), eq(MyProperties.class))).
thenReturn(myProperties);
mockStatic(UrlUtil.class);
doNothing().when(UrlUtil.class);
}
private void mockResponse() throws IOException {
PrintWriter writer = mock(PrintWriter.class);
140 --> doReturn(writer).when(response).getWriter();
}
}
doNothing().when(UrlUtil.class);
This doesn't mean anything to Mockito or PowerMock; you need to specify the specific call you want to mock. That makes this stubbing unfinished. See the PowerMockito when docs as an example.
However, Mockito can't tell on this line that your stubbing is unfinished—it can only raise an error when you interact with it, so it only detects the error condition later, in your mockCaptcha method.
To fix this, either finish your UrlUtil stub as follows (I specify PowerMockito to distinguish from Mockito.doNothing, though it looks like you have your static imports correct):
PowerMockito.doNothing().when(UrlUtil.class);
UrlUtil.methodYouWantToMock();
Or, to make UrlUtil suppress all its behavior by default, remove that doNothing line and put a default answer into your mockStatic call:
mockStatic(UrlUtil.class, RETURNS_SMART_NULLS);

UISpec4J tests in Eclipse are not found

I am trying to run tests using the UISpec4J library, but Eclipse says it can not find them. I have tried restarting Eclipse, cleaning the project, etc.
The class gives no errors and I have followed the examples given on the website.
package com.health.gui;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.uispec4j.Button;
import org.uispec4j.Panel;
import org.uispec4j.UISpec4J;
import org.uispec4j.UISpecTestCase;
import org.uispec4j.Window;
import org.uispec4j.interception.WindowInterceptor;
import com.health.gui.input.xmlwizard.XmlFilePanel;
public class TestXmlFilePanel extends UISpecTestCase {
static {
UISpec4J.init();
}
private Panel panel;
#BeforeClass
public void setUp() {
panel = new Panel(new XmlFilePanel());
}
#Test
public void editWithoutSelectedTest() {
Button edit = panel.getButton("Edit selected");
Window popup = WindowInterceptor.run(edit.triggerClick());
popup.titleEquals("Warning!");
}
}
I get the following stacktrace:
junit.framework.AssertionFailedError: No tests found in com.health.gui.TestXmlFilePanel
at junit.framework.Assert.fail(Assert.java:57)
at junit.framework.TestCase.fail(TestCase.java:227)
at junit.framework.TestSuite$1.runTest(TestSuite.java:100)
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:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
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 really have no clue what is wrong. Maybe you have some suggestions?
just for fun. you can remove "extends UISpecTestCase" in your class and give it a try see if it works or not :)
Junit 4.X should support annotation well and I didn't see any reason you need to extends UISpecTestCase.

Junit Testing with SpringFramework, without Maven : Error - NoSuchMethodError

I'm new with JUnit - Spring Framework.
What I'm doing is, creating some Tests for my Application. Here is Code what I have did.
#RunWith(SpringJUnit4ClassRunner.class)
public class InspirdTests {
#Autowired
private PlatformBLL platform;
#Autowired
private WebApplicationContext webAppContext;
#Before
public void settingUp(){
System.out.println("Before SetUp");
}
#Test
public void setUp() throws Exception{
System.out.println("Before : " + platform);
platform.getAllProjectsForPlatform(null);
System.out.println("After : " + platform);
}
}
and the Stack Trace
java.lang.NoSuchMethodError: org.junit.runner.notification.RunNotifier.testAborted(Lorg/junit/runner/Description;Ljava/lang/Throwable;)V
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:155)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:61)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:54)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:52)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:97)
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'm just blocked, Im stucked with it, i just cant move ahead.
What I have tried:
A lot google, but the result is as it is.
I had made some blank Methods for Testing, Still Result is as it is.
I have added JUnit-4.12.jar into WEB-INF/lib/
I have added Junit 4 into Java Build Path
Guys please Help me to Find out Solution for it.
Include spring-test and junit jars in your eclipse buildpath.
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
#ContextConfiguration(locations = { "classpath:/conf/applicationContext.xml"})
#RunWith(SpringJUnit4ClassRunner.class)
public class MongoRepositoryImplTest {
#Autowired
MongoRepositoryImpl mongoRepositoryImpl;
#Test
public void testGetMongoConnectionFromFactory() {
...
}
...
Config file should look like:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<context:component-scan base-package="com.client.impl" />
<bean id="mongoRepositoryImpl" class="com.client.impl.MongoRepositoryImpl">
<constructor-arg name="connectionName" value="testCases"/>
</bean>
</beans>

Spring ROO: JUnit test fails

I am having trouble executing my Spring IntegrationTests, when i run the code below it is failing at the persist method:
#RooIntegrationTest(entity = Person.class)
public class PersonIntegrationTest {
#Test
public void test() {
}
#Test
public void testCountPeople(){
Person personToPersist = PersonTestUtil.createTestPerson();
personToPersist.persist();
Long count = Person.countPeople();
assertNotNull(personToPersist);
assertTrue(personToPersist.countPeople() == 1);
}
}
The Stack trace is below
java.lang.IllegalStateException: Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)
at org.bixin.dugsi.domain.Person_Roo_Entity.ajc$interMethod$org_bixin_dugsi_domain_Person_Roo_Entity$org_bixin_dugsi_domain_Person$entityManager(Person_Roo_Entity.aj:95)
at org.bixin.dugsi.domain.Person.entityManager(Person.java:1)
at org.bixin.dugsi.domain.Person_Roo_Entity.ajc$interMethodDispatch1$org_bixin_dugsi_domain_Person_Roo_Entity$org_bixin_dugsi_domain_Person$entityManager(Person_Roo_Entity.aj)
at org.bixin.dugsi.domain.Person_Roo_Entity.ajc$interMethod$org_bixin_dugsi_domain_Person_Roo_Entity$org_bixin_dugsi_domain_Person$persist(Person_Roo_Entity.aj:58)
at org.bixin.dugsi.domain.Person.persist(Person.java:1)
at org.bixin.dugsi.domain.Person_Roo_Entity.ajc$interMethodDispatch1$org_bixin_dugsi_domain_Person_Roo_Entity$org_bixin_dugsi_domain_Person$persist(Person_Roo_Entity.aj)
at org.bixin.dugsi.domain.PersonIntegrationTest.testCountPeople(PersonIntegrationTest.java:25)
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 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.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)
Anyone run into this problem?
It seems that you have not injected the EntityManager and the related application context to your test.
Please try adding the following line above the class declaration.
#ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml","/META-INF/spring/applicationContext-security.xml" })
and try making your test class to inhert from AbstractJUnit4SpringContextTests. Do keep in mind that you might have to implement authentication for some operations to be executed.
Your test class could look like below.
package com.myapp.test;
#ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml","/META-INF/spring/applicationContext-security.xml" })
public class TestMyService extends AbstractJUnit4SpringContextTests {
#Autowired
MyService service = new MyService();
private void setUp() {
//Do the setting up of your classes for the test
}
#Test
public void testOperation() throws IOException {
//My Test Code here
}
}
Note that you should generally have a different context for your testing purposes.
Cheers.
If you're using Springsource Tool Suite (or another Eclipse) try to clean the project. I think Eclipse someimes doesn't use the AJDT Compiler, specially at startup.
I don't remember this message from the Roo console, that uses maven under the hood.
Try "perform eclipse" from the Roo shell or even maven directly from the console (mvn clean install or something like that)
It seems that you forgot to inject the EntityManager and the application context.
Try something like this, it worked for me with Spring Roo:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.jitter.finance.analyzer.domain.Address;
#ContextConfiguration(locations = { "classpath*:/META-INF/spring/applicationContext*.xml"})
public class EmTest extends AbstractJUnit4SpringContextTests {
#Test
public void checkEm(){
Address a = new Address();
a.setName("Primo");
a.persist();
Address b = new Address();
b.setName("Secondo");
b.persist();
for(Address ad : Address.findAllAddresses()){
System.out.println(ad.getName());
assertEquals(ad.getName().charAt(ad.getName().length()-1), 'o');
}
}
}

Categories

Resources