1

Let's say I have the following code:

protected int returnFourtyTwo() {
    evilMethod(new Object, "");
    return 42;
}

protected static void evilMethod(Object obj, String string) {
    throw new RuntimeException("This is me being evil.");
}

What I'm trying to do is to run my returnFourtyTwo() method without throwing the runtime exception in my unit test. I've been able to use the suppress() method to bypass class constructors before just fine, but this is the first time I've had to bypass a static method (with more than one argument) in a non-static class. Unfortunately, resources on the topic are a bit scarce.

Miles Peterson
  • 265
  • 1
  • 4
  • 12

4 Answers4

1

Your only way out is to mock the static method, as mentioned by @Dave. You can do that with PowerMock.

See Mocking static methods with Mockito.

Community
  • 1
  • 1
Fred Porciúncula
  • 8,533
  • 3
  • 40
  • 57
0

Depending on how complicated your actual method implementation is, you could separate your return call from your exception throwing - then test on the return call which will not throw the exception. In a lot of cases it's best if strange ints such as 42 have their own variable anyway to explain what it corresponds too - If it is always 42, then it is static and final.

This is what I would do for your exact situation here, but I'm guessing this is a major simple abstraction from your actual problem so you probably still want to mock it as previously suggested.

static final int theAnswerToLife = 42;

protected int returnFourtyTwo() {
    evilMethod(new Object, "");
    return getTheAnswerToLife();
}

protected int getTheAnswerToLife() {
    return theAnswerToLife;
}

protected static void evilMethod(Object obj, String string) {
    throw new RuntimeException("This is me being evil.");
}
DoubleDouble
  • 1,493
  • 10
  • 25
0

I don't say it is a good approach, but at least it works and it is not that bad. you can do this :

  1. create a public method in your inTest class and move your static method call there
  2. in your unit test - you are testing inTest class - you can use a spy instead of mock for your inTest class
  3. just ask unit test to do nothing for that method!

down side? we have a public method instead of private

Example : I am unit testing the recyclerView Adapter :

I have a logger which has static method call so I moved all logs to a method

    fun logMe(message: String) {
       MyCrashAnalytics.leaveBreadcrumb(message)
    }

and in unit test we have:

   val underTest = MyAdapter(....)

then in tests or in setup method we can do this.

   val spiedUnderTest = spy(underTest)
   doNothing().`when`(spiedUnderTest).logMe(anyString())

Then we are good to go!

Vahab Ghadiri
  • 2,016
  • 20
  • 26
-3

In simple you can use @Ignore annotation to your method.