Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java `final` class and mocking

I'm developing a programming game where players will have access to an abstract class and extend it to control the behaviour of a robot. Because it is a programming game, I am trying to protect my game infrastructure so that players don't mess with the game instead of just the class that I give them; for this I make most of my classes final but now I can't mock them in my unit tests (mockito + testNG).

So I was wondering, how can I work around this? is there a way to maybe leave the classes non-final for testing and then somehow automatically 'final-ize' them at a later stage of the build cycle (i'm using maven in case it's relevant for the answer). I don't want to add another external library or change my mocking library.
If it's not possible, then a second question: is making a class final really secure? i saw some libraries that could remove the final classifier from bytecode, which makes me think that maybe then final is useless if it can be removed from an already compiled class

like image 858
Hilikus Avatar asked Oct 30 '12 13:10

Hilikus


1 Answers

First, you can't prevent people from messing with your game by declaring things 'final'. There are reflection tricks and whole code generation libraries that make it merely slightly inconvenient to get past this.

So, lose the finals, and then you can use jmock or whatever library you like to make mocks.

like image 123
bmargulies Avatar answered Oct 22 '22 22:10

bmargulies