1

I'm using Kotlin with Mockito. Given these dependencies:

    @Mock
    private lateinit var tokenService: TokenService

    @Mock
    private lateinit var jwtDecoder: JwtDecoder

    @Mock
    private lateinit var passwordEncoder: PasswordEncoder

    @Mock
    private lateinit var authManager: AuthenticationManager

    @Mock
    private lateinit var mailLoginUserService: MailLoginUserService

    @Mock
    private lateinit var simpleMailService: SimpleMailService

I though the following codes should be equivalent.

First Variant:

@InjectMocks
private lateinit var underTest: MailLoginService

Second Variant:

private lateinit var underTest: MailLoginService

    @BeforeEach
    fun setup() {
    underTest = MailLoginService(
            tokenService,
            jwtDecoder,
            passwordEncoder,
            authManager,
            mailLoginUserService,
            simpleMailService
        )
    }

I know that BeforeEach is called before every test giving a knew instance of the MailLoginService but I'm only running one test.

In the test I specified

given(passwordEncoder.encode(anyString()))
            .willReturn("EncodedPassword")

Inside the tested method of MailLoginService the method passwordEncoder.encode is called. With the second variant (the manual constructor call) everything works fine. But with the first variant (InjectMocks) I get the following error:

java.lang.NullPointerException: encode(...) must not be null

I'd like to use InjectMocks as it reduces Code. Does anybody know why this problem occurs and how to fix it?

abc
  • 23
  • 4
Niklas
  • 105
  • 8
  • 1
    This may help you: [link](https://stackoverflow.com/questions/40961057/how-to-use-mockito-with-junit5) - not sure about Kotlin, but you need to tell Mockito to run somehow (annotation or static method call). – Jonasz Aug 27 '23 at 13:02

0 Answers0