0

Let's say I have a class Foo and a method evilMethod:

class Foo {

    public void evilMethod() {
       // do sth
    }
}

Is there a way to write a test that would fail any time there is any invocation of this method in any class on the classpath? I mean, not when the method is invoked at runtime, but when it's declared in the code.

For example, the precense of this code in any class on the classpath should make the test fail:

if(false) {
    Foo f = new Foo();
    f.evilMethod(); // test fails because of that
}

What I want to achieve: I would like to annotate methods that should not be called in certain project, but need to be placed there for the use in another, and then write a test that makes sure annotated methods are not invoked anywhere indeed.

Torben
  • 3,805
  • 26
  • 31
siledh
  • 3,268
  • 2
  • 16
  • 29
  • A reflection approach would imply a runtime solution, which is something you explicitly exclude. The way I understand this, you are looking for a static code analyzer that finds invocations of annotated methods. Right? – reto Nov 13 '13 at 12:23
  • Yes, you are right. But you can get all methods or classes based on annotations or any other criteria using reflection, so I figured maybe you could do something similar with method invocations. – siledh Nov 13 '13 at 12:24
  • Do you want this analysis to be done during compilation or when the tests are being run? – Torben Nov 13 '13 at 12:28
  • I was thinking when the tests are being run. – siledh Nov 13 '13 at 12:31
  • 2
    Does this help? http://stackoverflow.com/questions/930289/how-can-i-find-all-the-methods-that-call-a-given-method-in-java – Torben Nov 13 '13 at 12:34

2 Answers2

2

I don't know if it is fixes your problem but FindBugs does a static code analysis for Java projects. Maybe you can define a rule there that covers your issue...

mvieghofer
  • 2,846
  • 4
  • 22
  • 51
  • Thanks! We already use FindBugs, so that would be a great solution (different from what I'm actually asking here, but maybe even better) – siledh Nov 13 '13 at 12:38
0

Despite you asking for it not to be tested at runtime (unless you just meant in production), personally I'd want to include the check as part of a unit test. Using Mockito it would look like this:

verify(mockFoo, never()).evilMethod();

Based on the answer:

https://stackoverflow.com/a/12863072/575766

If you're project code coverage is good, that should resolve the issue for you.

Community
  • 1
  • 1
Michael
  • 7,348
  • 10
  • 49
  • 86
  • That is a good thought, but I was hoping for some more out-of-the box solution, like: write a test that covers all methods ever with this annotation added and then forget about it. – siledh Nov 13 '13 at 12:46
  • I think you'll struggle with an out the box solution - a method that classes in my project were forbidden from calling would either be private / protected etc. or not present at all. – Michael Nov 13 '13 at 12:58