4

I am new to Java and haven't done much of unit testing in general.
Can someone tell me why final classes cannot be mocked?

Idos
  • 15,053
  • 14
  • 60
  • 75
Abhi
  • 237
  • 3
  • 8

2 Answers2

5

Most common mocking framework in the java world cannot mock final classes/methods because they are typically based on creating proxies. Creating proxies for final classes is not possible as we cannot subclass (extends) a final class.

However, there are some workarounds and solutions, many of which can be found here.

Community
  • 1
  • 1
Idos
  • 15,053
  • 14
  • 60
  • 75
2

JMockit is able to mock final classes, methods, static and private fields, because it is primarily based on java.lang.instrument package classes and on proxy objects creation.

Andrei_N
  • 437
  • 2
  • 15