2023-08-31

Mockito InjectMocks not working but constructor call does

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?



No comments:

Post a Comment