1. kubek2k
  2. Springockito
Issue #32 new

@DirtiesMocks not inherited

Matt Metlis
created an issue

The @DirtiesMocks annotation cannot be inherited the way that Spring's @DirtiesContext can (Spring made it inherited here). If you add the @DirtiesMocks annotation to the superclass and not the subclass, it simply does not take effect on the subclass.

Here's an example where the annotation is on the superclass, and test2 fails:

class Foo {
  public String getFoo() {
    return "Foo";
  }
}

@ContextConfiguration(loader = SpringockitoContextLoader.class, locations = {})
@TestExecutionListeners({DirtiesMocksTestContextListener.class})
@DirtiesMocks(classMode = DirtiesMocks.ClassMode.AFTER_EACH_TEST_METHOD)
class FooTestParent extends AbstractJUnit4SpringContextTests {}

@ContextConfiguration
public class DirtiesMocksTest extends FooTestParent {
  @ReplaceWithMock
  @Autowired
  private Foo mockFoo;

  @Test
  public void test1() {
    doThrow(new RuntimeException("This exception should only be thrown from test1.")).when(mockFoo).getFoo();
    try {
      mockFoo.getFoo();
    } catch (Exception ex) {
      // expected
    }
  }

  @Test
  public void test2() {
    mockFoo.getFoo();
  }
}

Here's the same example but the annotation is moved to the subclass, and test2 passes:

class Foo {
  public String getFoo() {
    return "Foo";
  }
}

@ContextConfiguration(loader = SpringockitoContextLoader.class, locations = {})
@TestExecutionListeners({DirtiesMocksTestContextListener.class})
class FooTestParent extends AbstractJUnit4SpringContextTests {}

@DirtiesMocks(classMode = DirtiesMocks.ClassMode.AFTER_EACH_TEST_METHOD)
@ContextConfiguration
public class DirtiesMocksTest extends FooTestParent {
  @ReplaceWithMock
  @Autowired
  private Foo mockFoo;

  @Test
  public void test1() {
    doThrow(new RuntimeException("This exception should only be thrown from test1.")).when(mockFoo).getFoo();
    try {
      mockFoo.getFoo();
    } catch (Exception ex) {
      // expected
    }
  }

  @Test
  public void test2() {
    mockFoo.getFoo();
  }
}

It would be nice if the @DirtiesMocks annotation could be inherited.

Comments (0)

  1. Log in to comment