Java - varargs causes NullPointerException - variadic-functions

I just search through the forum, but haven't found a similar problem.
My problem is that I get a NullPointerException when using a varargs Constructor.
I just needed varargs in one of my programmes and tried this solution of my Java book, but it doesn't work!
My code is the following:
/** The author list. */
private List<String> authors;
/**
* Instantiates a new book.
*
* #param title the book title
* #param year the year the book was written
* #param authors the authors
*/
public Book(String title, int year, String... author)
{
{...}
if (author.length < 1)
{
throw new IllegalArgumentException
("A book needs a least 1 author!");
}
for (String e : author)
{
this.authors.add(e);
}
}
I think this.authors.add(e) causes the NullPointerException, but I don't know how to handle it.
As Iam testing it via JUnit I will just write some function calls:
(btw. all my function calls are failing)
Book b1 = new Book("Eragon", 1990, "Eric Cartman", "Kenny");
Book b2 = new Book("Eragon", 1990, "Eric Cartman");
Stacktrace:
java.lang.NullPointerException
at de.imbus.training.itbbj.books.Book.<init>(Book.java:57)
at de.imbus.training.itbbj.books.BookTests.creationTestSuccessful(BookTests.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.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)
Thanks in advance :)
TLS

There's no indication that you've ever assigned a non-null value to this.authors. At some point you'll want something like:
this.authors = new ArrayList<String>();
Or just initialize it as part of the declaration:
private final List authors = new ArrayList();
Note that this is entirely independent of varargs. You could hard code your statements as:
this.authors.add("Foo");
this.authors.add("Bar");
and you'd get the same result.

Related

How to test kotlin coroutines that return Exception?

i am writing unit test for some usecase, but i found that after i add withContext(IO) in my repository and than i run my unit test again, everything works fine except the test that expect to be fail and return exception, I've read several sites about testing coroutines but I found nothing to solve it, maybe I missed something? this is my repository
class HaditsRepository #Inject constructor(
private val remote: IRemoteHaditsDatasource,
#IoDispatcher private val dispatcher: CoroutineDispatcher
): IHaditsRepository {
override fun getCategories(): Flow<ResultOf<GetCategoriesResponse>> {
return flow {
emit(ResultOf.Loading())
val result = withContext(dispatcher){ remote.getCategories() }
emit(ResultOf.Success(result))
}.catch { e->
emit(ResultOf.Failure(e))
}
}
}
this is my usecase
class GetCategoriesUsecase #Inject constructor(
private val repository: IHaditsRepository
) {
operator fun invoke() = repository.getCategories()
}
and this is my unit test
#OptIn(ExperimentalCoroutinesApi::class)
class GetCategoriesUsecaseTest {
// Mock Initialize
private lateinit var openMock: AutoCloseable
// Coroutines
private val testDispatcher = StandardTestDispatcher()
// System Under Test
private lateinit var sut: GetCategoriesUsecase
// Given Conditions
private suspend fun givenFailure(){
whenever(mockDSR.getCategories()).thenThrow(dummyException)
}
// Setup
#Before
fun setup(){
openMock = MockitoAnnotations.openMocks(this)
Dispatchers.setMain(testDispatcher)
val repository = HaditsRepository(mockDSR, testDispatcher)
sut = GetCategoriesUsecase(repository)
}
#After
fun close(){
openMock.close()
Dispatchers.resetMain()
}
....
// FAIL HEREEEEE
#Test
fun `(-) Given failure - When SUT is called - Then assert result has correct Response`(){
runTest {
// Given
givenFailure()
// When
val result = sut().last() as ResultOf.Failure
// Then
Assert.assertEquals(dummyException, result.exception)
}
}
}
and this is what I got after I ran the test
expected: java.lang.RuntimeException<java.lang.RuntimeException> but was: java.lang.RuntimeException<java.lang.RuntimeException>
java.lang.AssertionError: expected: java.lang.RuntimeException<java.lang.RuntimeException> but was: java.lang.RuntimeException<java.lang.RuntimeException>
at org.junit.Assert.fail(Assert.java:89)
at org.junit.Assert.failNotEquals(Assert.java:835)
at org.junit.Assert.assertEquals(Assert.java:120)
at org.junit.Assert.assertEquals(Assert.java:146)
at id.co.haditsku.usecase.GetCategoriesUsecaseTest$(-) Given failure - When SUT is called - Then assert result has correct Response$1.invokeSuspend(GetCategoriesUsecaseTest.kt:130)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:104)
at kotlinx.coroutines.test.TestDispatcher.processEvent$kotlinx_coroutines_test(TestDispatcher.kt:28)
at kotlinx.coroutines.test.TestCoroutineScheduler.tryRunNextTaskUnless$kotlinx_coroutines_test(TestCoroutineScheduler.kt:100)
at kotlinx.coroutines.test.TestCoroutineScheduler.advanceUntilIdleOr$kotlinx_coroutines_test(TestCoroutineScheduler.kt:120)
at kotlinx.coroutines.test.TestCoroutineScheduler.advanceUntilIdle(TestCoroutineScheduler.kt:113)
at kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt.runTestCoroutine(TestBuilders.kt:237)
at kotlinx.coroutines.test.TestBuildersKt.runTestCoroutine(Unknown Source)
at kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt$runTest$1$1.invokeSuspend(TestBuilders.kt:167)
at kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt$runTest$1$1.invoke(TestBuilders.kt)
at kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt$runTest$1$1.invoke(TestBuilders.kt)
at kotlinx.coroutines.test.TestBuildersJvmKt$createTestResult$1.invokeSuspend(TestBuildersJvm.kt:13)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:284)
at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:85)
at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:59)
at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:38)
at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
at kotlinx.coroutines.test.TestBuildersJvmKt.createTestResult(TestBuildersJvm.kt:12)
at kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt.runTest(TestBuilders.kt:166)
at kotlinx.coroutines.test.TestBuildersKt.runTest(Unknown Source)
at kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt.runTest(TestBuilders.kt:154)
at kotlinx.coroutines.test.TestBuildersKt.runTest(Unknown Source)
at kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt.runTest$default(TestBuilders.kt:147)
at kotlinx.coroutines.test.TestBuildersKt.runTest$default(Unknown Source)
at id.co.haditsku.usecase.GetCategoriesUsecaseTest.(-) Given failure - When SUT is called - Then assert result has correct Response(GetCategoriesUsecaseTest.kt:124)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
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.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker$2.run(TestWorker.java:176)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
pleaseee hellppp
There is a strange issue where equality checks of Exceptions fail across coroutine boundaries even though they should be the same. It seems to be related to Exceptions being recreated using reflection and is discussed in detail here. It is something that has been dealt with in the tests of libraries like Turbine. There they use a custom exception that avoids this problem like the following:
/**
* This type prevents coroutines from breaking referential equality by
* reflectively creating new instances.
*/
internal class CustomRuntimeException(
message: String?,
override val cause: Throwable? = null,
) : RuntimeException(message)
I've successfully used a similar approach. So this is what you'll want to use for your dummyException.

Groovy #SelfType generating error with runtime traits

If I run the code below
import groovy.transform.SelfType
interface StringProvider {
String getString()
}
class MyStringProvider implements StringProvider {
#Override
String getString() {
"MyString"
}
}
//#SelfType(StringProvider)
trait DoubleStringProvider {
String getDoubleString() {
String s = getString()
s + s
}
}
MyStringProvider provider = new MyStringProvider()
println "provider = ${provider} (${provider.class})"
def doubleProvider = provider.withTraits DoubleStringProvider
println "doubleProvider = ${doubleProvider} (${doubleProvider.class})"
println "getDoubleString() ${doubleProvider.getDoubleString()}"
it displays
provider = MyStringProvider#213860b8 (class MyStringProvider)
doubleProvider = MyStringProvider5_groovyProxy#3d36dff4 (class
MyStringProvider5_groovyProxy) getDoubleString() MyStringMyString
when I uncomment the #SelfType statement I get
provider = MyStringProvider#476a736d (class MyStringProvider)
org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed: DoubleStringProvider$TraitAdapterwrapper: -1: class
'DoubleStringProvider$TraitAdapter' implements trait
'DoubleStringProvider' but does not implement self type interface
'StringProvider' # line -1, column -1. 1 error
at
org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:311)
at
org.codehaus.groovy.control.ProcessingUnit.completePhase(ProcessingUnit.java:149)
at
org.codehaus.groovy.control.CompilationUnit$20.call(CompilationUnit.java:938)
at
org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:965)
at
org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:601)
at
org.codehaus.groovy.runtime.ProxyGeneratorAdapter.adjustSuperClass(ProxyGeneratorAdapter.java:225)
at
org.codehaus.groovy.runtime.ProxyGeneratorAdapter.(ProxyGeneratorAdapter.java:160)
at groovy.util.ProxyGenerator.createAdapter(ProxyGenerator.java:230)
at
groovy.util.ProxyGenerator.instantiateDelegateWithBaseClass(ProxyGenerator.java:205)
at
groovy.util.ProxyGenerator.instantiateDelegateWithBaseClass(ProxyGenerator.java:189)
at
groovy.util.ProxyGenerator.instantiateDelegate(ProxyGenerator.java:181)
at
groovy.util.ProxyGenerator.instantiateDelegate(ProxyGenerator.java:177)
at
org.codehaus.groovy.runtime.DefaultGroovyMethods.withTraits(DefaultGroovyMethods.java:19602)
at org.codehaus.groovy.runtime.dgm$841.doMethodInvoke(Unknown Source)
at
org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.invoke(PogoMetaMethodSite.java:49)
at
org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.call(PogoMetaMethodSite.java:70)
at
org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at
org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:115)
at
org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:127)
at ideaGroovyConsole.run(ideaGroovyConsole.groovy:25) at
groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:266)
at groovy.lang.GroovyShell.run(GroovyShell.java:376) at
groovy.lang.GroovyShell.run(GroovyShell.java:355) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566) at
org.codehaus.groovy.runtime.callsite.PlainObjectMetaMethodSite.doInvoke(PlainObjectMetaMethodSite.java:43)
at
org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSite.invoke(PogoMetaMethodSite.java:167)
at
org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.call(PogoMetaMethodSite.java:70)
at
org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:135)
at console.run(console.groovy:11) at
groovy.ui.GroovyMain.processReader(GroovyMain.java:571) at
groovy.ui.GroovyMain.processFiles(GroovyMain.java:490) at
groovy.ui.GroovyMain.run(GroovyMain.java:334) at
groovy.ui.GroovyMain.access$1400(GroovyMain.java:69) at
groovy.ui.GroovyMain$GroovyCommand.process(GroovyMain.java:295) at
groovy.ui.GroovyMain.processArgs(GroovyMain.java:134) at
groovy.ui.GroovyMain.main(GroovyMain.java:116) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566) at
org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:110)
at
org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:128)
I understand what the error is saying but how do I make it work?
def doubleProvider = (provider as StringProvider).withTraits DoubleStringProvider doesn't work but was worth a shot
As per the documentation http://docs.groovy-lang.org/next/html/gapi/groovy/transform/SelfType.html, you need to use #SelfType annotation when you want to compile the class statically. In your case you are adding the traits dynamically, so you don't have to worry about this. Moreover, (not 100% sure though) the annotation parameter requires class name not the interface name as compiler has to make sure that the given method has really been implemented!

Mockito NullPointerException while using any

I am trying to use Mockito like this :
Mockito.when(Mockito.any(ObjectMapper.class).readValue(Mockito.any(BufferedReader.class),Mockito.any(Class.class))).thenReturn(new Person("1","abc"));
This is from Jackson library .
public <T> T readValue(Reader src, Class<T> valueType)
The reason I am doing it is because the time I reach this point of the code there are a ton of objects which were created. Mocking on every step would take time.
Any reason why I am getting NPE when code reaches this mockito statement?
Stack Trace :
java.lang.NullPointerException
at com.prashant.flax.ShellTest.givenDirectoryHasFiles(ShellTest.java:139)
at com.prashant.flax.ShellTest.testExecute(ShellTest.java:61)
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.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
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.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)
As you can see it is in a given method(this method only has this piece of code) , so I can see while debugging, it reaches over there and crashes.
As Oliver mentioned in the comments, you can't apply when to happen to all objects. Mockito works via subclassing, so you have to create a mock instance using mock, spy, or a #Mock or #Spy annotation; customize the behavior; and then install the mock using dependency injection or other similar tricks.
As to why this happens, the return value for any() actually is null; matchers like any are only supposed to be used as arguments to when and verify, and Mockito can't produce a specialized instance of Class that represents "any Class", so Mockito returns a dummy value (null) and stores data on a specialized stack of argument matchers. Though Mockito has better error messages to alert you to this situation, your code NPEs before Mockito can give you a proper exception with usage examples.
For more about matcher return values and the stack, see my other SO answer on "How do Mockito matchers work?".
To extend on what #jeff-bowman said in his answer, any() returns null, so if you need something that doesn't return null, you can try this:
/**
* never returns null
*/
private inline fun <reified T> any(type: Class<T>): T = Mockito.any(type)
/**
* returns null
*/
private inline fun <reified T> any(): T = Mockito.any<T>()
For me the actual problem was that I was trying to mock a spy. When mocking a spy you have to use the doReturn or doAnswer methods. Otherwise the method of the spy will be actually called while trying to mock it and unexpected behavior can happen. E.g. when calling when with any(), any() will just return null. So it is likely that you will get an NullPointerException.
Here is a full example that demonstrates the bahavior:
package com.company;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
public class SpyTest {
public class Controller {
public String method(String arg) {
return arg.substring(0, 1);
}
}
#Test
public void withMockTest() {
Controller controllerMocked = mock(Controller.class);
when(controllerMocked.method(anyString())).thenReturn("42");
assertEquals("42", controllerMocked.method("FOO"));
}
#Test(expected = NullPointerException.class)
public void withSpyWhenThenReturnBreakingBecauseMethodToBeMockedIsActuallyBeingCalled() {
Controller controllerSpied = spy(new Controller());
when(controllerSpied.method(any())).thenReturn("42");
}
#Test
public void withSpyDoReturnWhen() {
Controller controllerSpied = spy(new Controller());
doReturn("42").when(controllerSpied).method(any());
assertEquals("42", controllerSpied.method("FOO"));
}
}

I cant acces to static content of my HomePage inheritance from geb.Page

I cant continue, I am newbie in geb automation, I was trying to access to a element within of a geb.page, but i am getting an error, I am using Intellij like ide, please could someone help me please? my class structure and error message are the next:
The Page class
import geb.Page
class HomePage extends Page{
static url = "http://www.websitetest.com"
static at={
assert $("h1").text() == "Test website speed and performance"
}
static content ={
loginLink { $("a", text: "login")}
}
}
The test
void test(){
Browser.drive(){
to HomePage
loginLink.click()
}
}
Log/Trace
[TestNG] Running:
C:\Users\name.lastname\.IdeaIC14\system\temp-testng-customsuite.xml
groovy.lang.MissingPropertyException: No such property: loginLink for class: FirstTest
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:231)
at FirstTest$_test_closure1.doCall(FirstTest.groovy:14)
at FirstTest$_test_closure1.doCall(FirstTest.groovy)
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.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:278)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1016)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:39)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
at geb.Browser.drive(Browser.groovy:701)
at geb.Browser$drive$2.callStatic(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallStatic(CallSiteArray.java:53)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callStatic(AbstractCallSite.java:157)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callStatic(AbstractCallSite.java:169)
at geb.Browser.drive(Browser.groovy:671)
at geb.Browser$drive.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at FirstTest.test(FirstTest.groovy:12)
===============================================
Custom suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================
Process finished with exit code 0
You have to use keyword 'at' to fetch declarations from content block and let elements inside it be used. Try this one:
void test(){
Browser.drive(){
to HomePage
at HomePage
loginLink.click()
}
}

Why does Groovy think I'm passing an instance of the class from a static method?

I'm new to Groovy, so it's likely I am doing something wrong. I had written a configuration to be taken in by ConfigSlurper. But something goes wrong when I actually try to parse it. My code is as follows:
class CharacterMap {
public static final String CHARACTER_CONFIGURATION = 'location'
static Map<String,String> characterMap = null
public static String ASCIIize(String input)
{
if (!characterMap)
{
def property = System.getProperty( CHARACTER_CONFIGURATION )
ConfigObject config = null
if( property ) {
ConfigSlurper cs = new ConfigSlurper()
File file = new File( property )
URL location = file.toURL()
config = cs.parse(location)
}
if (config)
{
characterMap = config.characters
}
else
{
getAnonymousLogger().logp WARNING, getClass().name, 'constructor',
"Server configuration groovy file not configured with system property ${CHARACTER_CONFIGURATION}"
return input
}
}
for (String key: characterMap.keySet())
{
if (input.contains(key))
{
input = input.replace(key, characterMap.get(key))
}
}
return input
}
public static void main(String[] args)
{
print ASCIIize(args[0])
}
}
When it gets to calling the parse method it complains Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: groovy.util.ConfigSlurper.parse() is applicable for argument types: (CharacterMap, java.net.URL)
As you can see, I am only passing in one argument, which was declared to be a URL. Since all the methods of the class are static and no constructor is referenced anywhere, it's kind of bizarre that an instance is being created at all, and more bizarre still that it's being passed into the parse method. I've read other people on Stack Overflow getting MissingMethodException (though usually related to closures rather than superfluous arguments), and it being blamed on Eclipse. I am running this in IntelliJ rather than Eclipse.
EDIT: In response to the comment below the groovy version is 1.8.6. Here is the stack-trace:
Exception in thread "main" groovy.lang.MissingMethodException: No
signature of method: groovy.util.ConfigSlurper.parse() is applicable
for argument types: (CharacterMap, java.net.URL) values:
[CharacterMap#34374a16, file:/C:/Program Files
(x86)/JetBrains/IntelliJ IDEA Community Edition
11.1.2/UCP/config/CharacterMap.groovy]
Possible solutions: parse(java.net.URL), parse(groovy.lang.Script,
java.net.URL), parse(groovy.lang.Script), parse(java.lang.Class),
parse(java.lang.String), parse(java.util.Properties)
at
org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55)
at
org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:78)
at
org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:46)
at
org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
at
org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:145)
at groovy.util.ConfigSlurper.parse(ConfigSlurper.groovy:148) at
groovy.util.ConfigSlurper$parse.call(Unknown Source) at
org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at
org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at
org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at ucp.cms.search.CharacterMap.ASCIIize(CharacterMap.groovy:26) at
ucp.cms.search.CharacterMap.main(CharacterMap.groovy:51) 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
com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Process finished with exit code 1

Resources