I have started testing and now i want to use @After
, @Before
and @Test
but my application only runs the @Before
method and gives output on console
before
However, if I remove @After
and @Before
it runs the @Test. My code is here:
public class TestPractise extends AbstractTransactionalDataSourceSpringContextTests{
@Before
public void runBare(){
System.out.println("before");
}
@Test
public void testingMethod(){
System.out.println("testing");
}
@After
public void setDirty(){
System.out.println("after");
}
}
Why aren't @After
, @Test
and @before
working simultaneously?
Use
@BeforeEach
instead of@Before
and@AfterEach
instead of@After
.It should work... But since you are working with spring framework and JUnit 4 was introduced years ago I's suggest you to use annotations instead of inheritance.
So, annotate you class with
@RunWith(SpringJUnit4ClassRunner.class)
. Removeextends AbstractTransactionalDataSourceSpringContextTests
.Don't forget to make the @Before and @After methods static
Now it should work.
Even if you want to extend Spring abstract test classes at least pay attention that some of them are deprecated. For example class
AbstractTransactionalDataSourceSpringContextTests
is deprecated.The
AbstractTransactionalDataSourceSpringContextTests
class forces the use of the old JUnit 3.x syntax, which means that any of the JUnit 4 annotation will not work.Your method
runBare()
is executed not because of the@Before
annotation, but because it is namedrunBare()
, which is a method provided byConditionalTestCase
and JUnitTestCase
class.So you have 2 solutions:
AbstractTransactionalDataSourceSpringContextTests
, but use theonSetUp
andonTearDown
methods instead of the@Before
and@After
methods.