1

I have a configuration property class, annotated with @ConstructorBinding to make it immutable. But while running test cases, this is not getting mocked.

@ConfigurationProperties
@ConstructorBinding
@lombok.Value
class PropertyConfig{
// some code
}

While running the test classes, I'm getting the following error:

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class com.packagename.PropertyConfig
Mockito cannot mock/spy because :
 - final class
    at 

How to fix this error?

m23
  • 61
  • 1
  • 2
  • 6
  • 1
    hi & welcome! :wave - "Immutable" it is by `@Value` (not by `@ConstructorBinding`). - Why mocking a `@Value`? (just create one(..., and pass mocks to constructor;)) – xerx593 Nov 16 '21 at 08:22
  • ..but [with mockito 2, you obviously can also "hack" final class](https://stackoverflow.com/q/14292863/592355);) – xerx593 Nov 16 '21 at 08:29

1 Answers1

0

Your annotation @lombok.Value implies that your class is final and this is not directly supported by mockito.

Since this is a configuration class, it probably doesn’t need to be mocked anyway, you can simply instantiate it by calling the constructor normally.

If you really need to mock it for some reason, see this question How to mock a final class with mockito, or do not use @Value.

WilQu
  • 7,131
  • 6
  • 30
  • 38