How to test that all methods of a class is not called in jMock?

458 Views Asked by At

Using jMock, how do I test that all methods of a certain class is not called upon invoking a method in another class?

For example, if I have class A and class B:

class A {
    void x() {
    }
    void y() {
    }
    void z() {
    }
}

class B {
    A a;
    void doNothing() {
    }
}

How do I test that the invocation of B#doNothing() doesn't invoke any of class A's method?

I know that with jMock 2 and JUnit 3, I can do:

public class BTest extends MockObjectTestCase {
    @Test
    public void testDoNothing() {
        B b = new B();
        A a = b.getA();
        checking(new Expectations() {{
            never(a).x();
            never(a).y();
            never(a).z();
        }});
        b.doNothing();
    }
}

But what if there is more than just 3 methods, say 30? How would I test that?

1

There are 1 best solutions below

0
Daniel Martin On

First off, I believe that is will in fact match what you want:

public class BTest extends MockObjectTestCase {
    @Test
    public void testDoNothing() {
        B b = new B();
        A a = b.getA();
        checking(new Expectations() {{
            never(a);
        }});
        b.doNothing();
    }
}

However, if that doesn't work, this should:

import org.hamcrest.Matchers;
// ...

public class BTest extends MockObjectTestCase {
    @Test
    public void testDoNothing() {
        B b = new B();
        A a = b.getA();
        checking(new Expectations() {{
            exactly(0).of(Matchers.sameInstance(a));
        }});
        b.doNothing();
    }
}