@After, @ before not working in a test

I started testing, and now I want to use @After , @Before and @Test , but my application only runs the @Before method and prints to the console

before

However, if I delete @After and @Before , it runs @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 don't @After , @Test and @Before ?

+6
source share
2 answers

The AbstractTransactionalDataSourceSpringContextTests class forces you to use the old JUnit 3.x syntax, which means that any of the JUnit 4 annotations will not work.

Your runBare() method does not execute because of the @Before annotation, but because it is called runBare() , which is the method provided by ConditionalTestCase and JUnit TestCase .

So you have 2 solutions:

  • Use AlexR's answer to use JUnit 4 and Spring tests;
  • Keep the inheritance of AbstractTransactionalDataSourceSpringContextTests , but use the onSetUp and onTearDown methods instead of the @Before and @After .
+10
source

It should work ... But since you are working with the spring framework, and JUnit 4 was introduced many years ago, I suggest you use annotations instead of inheritance.

So annotate the class with @RunWith(SpringJUnit4ClassRunner.class) . Remove extends AbstractTransactionalDataSourceSpringContextTests .

Remember to make @Before and @After static methods

Now that should work.

Even if you want to extend the spring testing classes, at least note that some of them are deprecated. For example, the AbstractTransactionalDataSourceSpringContextTests class is deprecated.

+3
source

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


All Articles