This is my test method:
#RunWith(Parameterized.class)
#PrepareForTest(FilenameUtils.class)
public class Test {
//code
private final String datum;
private final String expectedResult;
public Test(String datum, String expectedResult){
this.datum = datum;
this.expectedResult = expectedResult;
}
#Parameters
public static Collection<Object[]> generateData(){
return Arrays.asList(new Object[][] {
{ ".jpg", "productimage..jpg" },
{ "jpg", "jpg.jpeg" },
{ "thequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydog.jpeg", "thequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjump.jpeg" }
});
}
#Before
public void setUp() {
}
#After
public void tearDown() {
}
#Test
public void testSanitizeFilename(){
PowerMock.mockStaticPartial(FilenameUtils.class, "getExtension" , "getBaseName");
expect(FilenameUtils.getExtension(datum)).andReturn("jpeg").anyTimes();
expect(FilenameUtils.getBaseName(datum)).andReturn("productimage").anyTimes();
PowerMock.replay(FilenameUtils.class);
String result = FileUtil.sanitizeFilename(datum, defaultName, contentType);
PowerMock.verify(FilenameUtils.class);
assertEquals(result, expectedResult);
}
}
And this is the method to be tested:
public class FileUtil {
//code
public static String sanitizeFilename(String filename, ............) {
//code here
if (filename.length() > 100) {
FilenameUtils.getExtension(fileName);
FilenameUtils.getBaseName(fileName);
}
return fileName;
}
}
The code works only for the cases that the condition in FileUtil.sanitizeFilename is not true. If it is true (by passing a filename > 100 characters), then the following error occurs:
Unexpected method call FilenameUtils.getExtension("thequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydog.jpeg"):
java.lang.AssertionError
Unexpected method call FilenameUtils.getExtension("thequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydog.jpeg"):
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl.invoke(EasyMockMethodInvocationControl.java:91)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:105)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:60)
at org.apache.commons.io.FilenameUtils.getExtension(FilenameUtils.java)
at com.eurodyn.ecatalogue.util.FileUtil.sanitizeFilename(FileUtil.java:235)
at com.eurodyn.ecatalogue.ejb.session.others.AsyncFileDownloadManagerBeanTest.testSanitizeFilename(AsyncFileDownloadManagerBeanTest.java:130)
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.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.powermock.modules.junit4.rule.PowerMockStatement$1.run(PowerMockRule.java:52)
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.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:2014)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:885)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:713)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
at org.powermock.classloading.ClassloaderExecutor.execute(ClassloaderExecutor.java:98)
at org.powermock.classloading.ClassloaderExecutor.execute(ClassloaderExecutor.java:78)
at org.powermock.modules.junit4.rule.PowerMockStatement.evaluate(PowerMockRule.java:49)
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.junit.runners.Suite.runChild(Suite.java:127)
at org.junit.runners.Suite.runChild(Suite.java:26)
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.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
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.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
What is incorrect in my code?
EDIT:
I used Parameterized class in order to avoid the for loop.
I used PowerMock.mockStaticPartial for the static methods getBaseName and getExtension.
How it worked for me
#Test
public void testSanitizeFilename() {
PowerMock.mockStatic(FilenameUtils.class);
EasyMock.expect(FilenameUtils.getExtension(anyString())).andReturn("jpeg").anyTimes();
EasyMock.expect(FilenameUtils.getBaseName(anyString())).andReturn("jpeg").anyTimes();
PowerMock.replayAll();
for (Map.Entry<String, String> entry : fileUrls.entrySet()) {
System.out.println("KEY: " + entry.getKey());
String result = FileUtil.sanitizeFilename(entry.getKey(), entry.getValue());
assertEquals(result, entry.getValue());
PowerMock.verifyAll();
}
}
Note that I modified sanitizeFilename some to get working code for me. And I used
#Rule
public PowerMockRule rule = new PowerMockRule();
instead of RunWith - but as I had all your errors before this might fix your stuff as well.
Seems like mocking inside the loop was no good idea to begin with - once I moved the mocks out of the loop it got me somewhere.
Related
Here's my unit test that I expect to pass:
import static org.junit.Assert.assertEquals;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Test;
import com.google.common.collect.ImmutableSet;
public class JMockTest {
#Test
public void test() {
Mockery mockery = new Mockery();
final Foo foo = mockery.mock(Foo.class);
mockery.checking(new Expectations() {{
oneOf(foo).bar(); will(returnValue(ImmutableSet.<Long>of()));
}});
ImmutableSet<Long> result = foo.bar();
assertEquals(ImmutableSet.<Long>of(), result);
}
interface Foo {
ImmutableSet<Long> bar();
}
}
However, it throws this error instead:
java.lang.reflect.UndeclaredThrowableException
at $Proxy3.bar(Unknown Source)
at JMockTest$1.<init>(JMockTest.java:17)
at JMockTest.test(JMockTest.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
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)
Caused by: java.lang.IllegalAccessException: Class org.jmock.internal.ReturnDefaultValueAction can not access a member of class com.google.common.collect.ImmutableSet with modifiers ""
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
at java.lang.Class.newInstance(Class.java:436)
at org.jmock.internal.ReturnDefaultValueAction.collectionOrMapInstanceFor(ReturnDefaultValueAction.java:87)
at org.jmock.internal.ReturnDefaultValueAction.invoke(ReturnDefaultValueAction.java:77)
at org.jmock.internal.InvocationToExpectationTranslator.invoke(InvocationToExpectationTranslator.java:20)
at org.jmock.internal.FakeObjectMethods.invoke(FakeObjectMethods.java:38)
at org.jmock.lib.JavaReflectionImposteriser$1.invoke(JavaReflectionImposteriser.java:33)
... 26 more
It seems that JMock is internally attempting to instantiate an ImmutableSet, even though I provided one for it.
See ReturnDefaultValueAction:
private Object collectionOrMapInstanceFor(Class<?> returnType) throws Throwable {
return returnType.isInterface() ? instanceForCollectionType(returnType) : returnType.newInstance();
}
returnType.isInterface() is false b/c it's a ImmutableSet, so JMock calls ImmutableSet.newInstance(), which fails b/c ImmutableSet does not have an accessible constructor.
I assume that people other than me have mocked interfaces that return guava immutable collection objects before, or interfaces that return classes with no visible constructor. How do you deal with this in JMock?
EDIT: This is JMock 2.6.0
EDIT2: This works in JMock 2.8.2!
This seems like a bug with your version of JMock, 2.6.0, as you've described it. Upgrade to the latest, currently 2.8.2. The issue will go away.
I am using Jetty client API on my application and I want to test my following code using Junit and Mockito:
public void startHttpClient(){
try {
httpClient.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My test case is the following:
#Mock HttpClient httpClient;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
testBackend= new TestBackend(3,httpClient);
}
#Test
public void teststartHttpClient() throws Exception {
testBackend.startHttpClient();
assertNotNull(httpClient);
verify(httpClient,atLeastOnce()).start();
}
The problem is that the Mock HttpClient inherit the start() method from AbstractLifeCycle, so I got a null pointer exception on the AbstractLifeCycle class:
How can I mock the inherited method start() call fot the class HttpClient?
The Exception got:
java.lang.NullPointerException
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:61)
at test.TestBackendTest.teststartHttpClient(TestBackendTest.java:75)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.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 having difficulties understanding how to mock/stub an interface with Mockito.
This simple scenario...
public interface Adder
{
int add(int a, int b);
}
public class Calculator
{
Adder _adder;
public Calculator(Adder adder)
{
_adder = adder;
}
public int add(int a, int b)
{
return _adder.add(a, b);
}
}
public class MockitoTester
{
#Test
public void can_mock()
{
Adder adder = mock(Adder.class);
Calculator sut = new Calculator(adder);
assertThat(sut).isNotNull();
}
}
Is giving me this error...
java.lang.NoClassDefFoundError: net/bytebuddy/dynamic/scaffold/subclass/ConstructorStrategy
at org.mockito.internal.creation.bytebuddy.CachingMockBytecodeGenerator.<init>(CachingMockBytecodeGenerator.java:20)
at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.<init>(ByteBuddyMockMaker.java:22)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at java.lang.Class.newInstance(Class.java:442)
at org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:33)
at org.mockito.internal.configuration.plugins.PluginRegistry.<init>(PluginRegistry.java:12)
at org.mockito.internal.configuration.plugins.Plugins.<clinit>(Plugins.java:11)
at org.mockito.internal.util.MockUtil.<clinit>(MockUtil.java:23)
at org.mockito.internal.MockitoCore.<init>(MockitoCore.java:44)
at org.mockito.Mockito.<clinit>(Mockito.java:1101)
at com.jnericks.testutils.MockitoTester.can_mock(MockitoTester.java:13)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
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.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:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.lang.ClassNotFoundException: net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 40 more
Mockito depends on the artifact net.bytebuddy:byte-buddy. See this POM definition from the Maven repositories. Make sure you get the mockito-all artifact which includes all dependencies in one Jar.
If you are using Maven, then it should automatically resolve the dependency when using mockito-core. You can run mvn dependency:tree on the project to see the hierarchy of your project's dependencies.
I am running a simple JUnit test. The test is:
private HangmanModel model;
private WordsToGuess word;
public void setUp()
{
model = new HangmanModel();
word = new WordsToGuess();
}
#Test
public void addWordAndChoose()
{
WordsToGuess testWord = new WordsToGuess("ahoy");
model.addWord(testWord); <---- NullPointerException
String foundWord = model.randomWord();
assertEquals("Not found the word", testWord, foundWord);
}
In WordsToGuess, the constructor is:
public WordsToGuess(String w)
{
word = w;
}
In HangmanModel, the addWord method is:
private ArrayList<WordsToGuess> words;
words = new ArrayList<WordsToGuess>();
public void addWord(WordsToGuess w)
{
words.add(w);
}
This is a REALLY weird NullPointerException since everything should run perfectly fine. It is copied almost word for word from a similar project. Here is the Stack trace:
java.lang.NullPointerException
at testing.HangmanModelTest.addWordAndChoose(HangmanModelTest.java:22)
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.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: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 #Before annotation is required before the setup method for JUnit 4
#Before
public void setUp() {
...
}
I have been trying to setup my test framework for Spring data neo4j (version 3.0.1.RELEASE) application. I am using pure java config to setup my test cases.
This is my TestConfig class
#Configuration
#EnableTransactionManagement
#EnableNeo4jRepositories(basePackages = {"com.sitename.data.repository"})
#ComponentScan(basePackages = "com.sitename.data")
public class TestDataConfig extends Neo4jConfiguration {
#Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
return new TestGraphDatabaseFactory().newImpermanentDatabase();
}
#Bean
public Neo4jTemplate neo4jTemplate() {
return new Neo4jTemplate(graphDatabaseService());
}
}
And this is my test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class TestClass {
private UserService userService = UserService.getInstance();
#BeforeClass
public static void setup() {
BaseService.configure(TestDataConfig.class);
}
#Before
public void addData() {
saveOneUser("test#email.com");
}
#Test
public void testMe() {
Assert.assertEquals(0, userService.findAll().size());
}
private User saveOneUser(String email) {
try {
User user = new User();
user.setEmail(email);
user.setFirstName( new Integer(new Random(new Date().getTime()).nextInt(17) + 1).toString() );
return userService.save( user );
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
return null;
}
}
Every time i run the test i am getting the Failed to mark transaction as rollback only error.
Full stacktrace
-------------------------------------------------------------------------------
Test set: com.sitename.TestClass
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 6.416 sec <<< FAILURE!
testMe(com.sitename.TestClass) Time elapsed: 0.406 sec <<< ERROR!
org.neo4j.graphdb.TransactionFailureException: Failed to mark transaction as rollback only.
at org.neo4j.kernel.TopLevelTransaction.markAsRollbackOnly(TopLevelTransaction.java:97)
at org.neo4j.kernel.TopLevelTransaction.failure(TopLevelTransaction.java:86)
at org.neo4j.cypher.internal.spi.v2_0.TransactionBoundExecutionContext.close(TransactionBoundExecutionContext.scala:58)
at org.neo4j.cypher.internal.compiler.v2_0.spi.DelegatingQueryContext.close(DelegatingQueryContext.scala:32)
at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext.org$neo4j$cypher$internal$compiler$v2_0$spi$ExceptionTranslatingQueryContext$$super$close(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext$$anonfun$close$1.apply$mcV$sp(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext$$anonfun$close$1.apply(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext$$anonfun$close$1.apply(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext.org$neo4j$cypher$internal$compiler$v2_0$spi$ExceptionTranslatingQueryContext$$translateException(ExceptionTranslatingQueryContext.scala:149)
at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext.close(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_0.ClosingIterator.failIfThrows(ClosingIterator.scala:94)
at org.neo4j.cypher.internal.compiler.v2_0.ClosingIterator.next(ClosingIterator.scala:45)
at org.neo4j.cypher.internal.compiler.v2_0.PipeExecutionResult.next(PipeExecutionResult.scala:168)
at org.neo4j.cypher.internal.compiler.v2_0.PipeExecutionResult.next(PipeExecutionResult.scala:34)
at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
at scala.collection.convert.Wrappers$IteratorWrapper.next(Wrappers.scala:30)
at org.neo4j.cypher.internal.compiler.v2_0.PipeExecutionResult$$anon$1.next(PipeExecutionResult.scala:76)
at org.neo4j.helpers.collection.IteratorWrapper.next(IteratorWrapper.java:47)
at org.neo4j.helpers.collection.IteratorWrapper.next(IteratorWrapper.java:47)
at org.neo4j.helpers.collection.IteratorUtil.addToCollection(IteratorUtil.java:478)
at org.neo4j.helpers.collection.IteratorUtil.addToCollection(IteratorUtil.java:557)
at org.springframework.data.neo4j.conversion.ContainerConverter.toContainer(ContainerConverter.java:34)
at org.springframework.data.neo4j.conversion.QueryResultBuilder$1.as(QueryResultBuilder.java:128)
at com.sitename.data.service.UserService.findAll(UserService.java:20)
at com.sitename.TestClass.testMe(TestClass.java:40)
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.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
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.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: java.lang.NullPointerException
at org.neo4j.kernel.TopLevelTransaction.markAsRollbackOnly(TopLevelTransaction.java:93)
... 60 more
Help is appreciated. TIA !
Try and add
#Transactional
on top of your test class to run your tests within a transaction.