Skip to content

Any() throws method must not be null #395

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
mtwolak opened this issue Nov 26, 2020 · 3 comments
Open

Any() throws method must not be null #395

mtwolak opened this issue Nov 26, 2020 · 3 comments

Comments

@mtwolak
Copy link

mtwolak commented Nov 26, 2020

Hi,

I'm mocking spring repository with signature:

JpaRepository<Entity, Id> {
   <S extends Entity> S save(S entity);
}

Here is my try:

val mockRepository = mock<JpaRepository> {
            on { save(any()) } doThrow RuntimeException("Some exception")
        }

But then I got
Caused by: java.lang.NullPointerException: save(any()) must not be null
In order to fix this, I must do ugly thing, specyfing generic type like:

val mockRepository = mock<JpaRepository> {
            on { save(any<Entity>()) } doThrow RuntimeException("Some exception")
        }

And it works, but IDE (Intellij) is suggesting generic removal: Remove explicit type arguments
So I tried something else:

val mockRepository = mock<JpaRepository> {
            on { save(Mockito.any(Entity::class.java)) } doThrow RuntimeException("Some exception")
        }

and IDE is not complaining at all, but it looks ugly. Any better solution?

@bohsen
Copy link

bohsen commented Nov 26, 2020

@mtwolak This is a java-kotlin interop issue I believe and is caused by javas missing null-safety.

Try doThrow(IllegalStateException::class).whenever(mock).go().

@usr42
Copy link

usr42 commented Apr 16, 2021

@mtwolak I your scenario you can also use onGeneric instead of on. Then it should work without explicit type.

But I have a similar issue but I don't want/can specify the mock behavior when the mock is created, but only inside the test. So I usually use something like:

whenever(repository.save(any())).doReturn(entity)

But this also fails without specifying the type exlicitly in the any (any<Entity>()). Is there something similar to onGeneric but for the whenever workflow.

Any help or hint is appreciated.

@dmaiken
Copy link

dmaiken commented May 6, 2025

Very late to this party, but you can get around this issue specifically:

whenever(repository.save(any())).doReturn(entity)

by doing something like this:

whenever(repository.save(any<YourEntityClass>()).thenAnswer {
    it.arguments[0] as YourEntityClass
}

You must specify the type in any() otherwise I get an NPE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants