How to unit test Java code that is expected to run

2019-05-16 18:17发布

问题:

I have some Java library code which sometimes runs as an unsigned applet. Because of this it is not always allowed to do some operations (for instance checking for system properties).

I would like to run some unit tests with an Applet-like security manager so that I can verify that the code is either not performing any restricted operations, or correctly handling any security exceptions.

What is the best way to run these unit-tests with a realistic Security-Manager configuration? Preferable the solution would be something that can integrate with JUnit.

回答1:

Not a solution as such, but couldn't you implement your own subclass of SecurityManager, perhaps delegating all calls to a 'pseudo security manager' which would in turn be mocked by EasyMock/similar? You could then set this SecurityManager using System.setSecurityManager().

Provided you know what your applet should be able to do, you can then fail the test depending on your requirements.

I may have missed what you want to achieve, but that seems like one possible approach.