Testing a specific third-party class with JMock

I have a class with a forwarding method foo:

void foo( Concrete c, String s ) { c.bar( s ); }

I want to check if it really footranslates. Unfortunately, for me it Concreteis a class in a third-party library and represents a specific type, not an interface. So I have to use ClassImposteriserin JMock for mock Concrete, so in my test case I do this:

@Test
public final void testFoo() {
   Mockery context = new JUnit4Mockery() {{
      setImposteriser(ClassImposteriser.INSTANCE);
   }};

  final Concrete c = context.mock(Concrete.class);
  final String s = "xxx" ;

  // expectations
  context.checking(new Expectations() {{

     oneOf (c).bar(s); // exception gets thrown from here
  }});


  new ClassUnderTest.foo( c, s );
  context.assertIsSatisfied();

}

Unfortunately, it Concrete.barin turn calls a method that throws. This method is final, so I cannot override it. Also, even if I comment out a line new ClassUnderTest.foo( c, s );, an exception occurs when JMock sets exceptions, and not when it is called foo.

, , ClassUnderTest.foo Concrete.bar?

Edit:
, .

, , , "" Concrete.

+3
4

, Concrete.bar() , Concrete.somethingElse() Concrete.bar().

Concrete.bar() , Concrete :

public class ConcreteStub extends Concrete
{
    public int numCallsToBar = 0;
    @Override
    public void bar(String s) { numCallsToBar++; }
}

:

ConcreteStub c = new ConcreteStub();
foo(c,"abc");
assertEquals(1,c.numCallsToBar);

Concrete.bar() , , Concrete Concrete. Concrete , Concrete ( " " ), .

: , Concrete. .

: . , Concrete, Concrete .

+5

, . , , . , , , .

0

, JMockit. :

@Test
public void testFoo(final Concrete c)
{
  final String s = "xxx";

  new Expectations() {{
    c.bar(s);
  }};

  new ClassUnderTest().foo(c, s);
}

For JMockit, it does not matter if it Concreteis an interface, the last class, an abstract class, or something else. In addition, there is no need to use @RunWith, extend the base test class, or call any method, for example assertIsSatisfied(); all this is done automatically, in a transparent way.

0
source

Source: https://habr.com/ru/post/1706288/


All Articles