0

In JMockit, there are types that are outright un-mockable (like java.lang.Class) or are really bad ideas to mock (like java.lang.Math, as stated in this question).

How do you use Verifications on these types? Using the linked question as an example, how would I verify that Math.pow() got called with the right arguments?

By way of example, this test passes even though I call Math.pow() but I check for Math.min() in the Verifications - how could I make this fail?

public class TestTest {

    public static class MyClass {
        public double foo() {
            return Math.pow(2, 3);
        }
    }

    @Tested MyClass mc;
    // @Mocked java.lang.Math math;

    @Test
    public void testCalendar() throws Throwable {
        double d = mc.foo();
        assertThat(d, is(8.0));
        new FullVerificationsInOrder() {{
            Math.min(42.0, 17.0);
        }};
    }
}

Adding the commented-out line, to mock Math, only leads to disastrous results due to fouling up classloaders etc that rely on java.lang.Math. Making it @Injectable instead of @Mocked has no effect since all methods are static.

So how could I verify it?

Community
  • 1
  • 1
dcsohl
  • 7,186
  • 1
  • 26
  • 44
  • The example test is meaningless, as the method `foo` always returns the constant value `8`. *How* it gets to that result is an irrelevant implementation detail, and mocking is not meant to be used for checking implementation details. It's hard to imagine any legitimate test that would need to check whether a method like `Math.pow` gets called or not. So, the best answer for a question like this, IMO, is: you *don't* "use Verifications" in such cases. – Rogério Mar 01 '16 at 16:46
  • So there's no way to use a Verification on a class without mocking it? And in your view, no need to verify these sorts of low-level classes? Hmmm, I'll have to think on this a little more. I haven't actually experienced any issues myself; it was more that the related question prompted this question to mind, so ... as I said, I'll have to think on it some more. – dcsohl Mar 01 '16 at 16:51
  • I agree with @Rogerio. I would recommend testing a higher level behavior. If you were to insist, however, on verifying that the exponentiation is taking place, you can always use another level of indirection: wrap the `Math` functions with a class of your own and mock your class. After all, the fact that you are using `Math` for your mathematical needs is an implementation detail. – beluchin Mar 03 '16 at 11:24

0 Answers0