Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@After ,@before not working in testcase

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?

like image 842
abhishek ameta Avatar asked May 14 '12 09:05

abhishek ameta


People also ask

Does @after run after every test?

 @After - method that is run after every test case.

Does @before run before each test?

Methods annotated with the @Before annotation are run before each test.

What is @before in JUnit test?

The @Before annotation is used when different test cases share the same logic. The method with the @Before annotation always runs before the execution of each test case. This annotation is commonly used to develop necessary preconditions for each @Test method.

What is the use of @before and @after in JUnit?

This base class has a @Before ( public void setUp() ) and @After ( public void tearDown() ) method to establish API and DB connections.


2 Answers

Use @BeforeEach instead of @Before and @AfterEach instead of @After.

like image 179
vikram k Avatar answered Sep 23 '22 01:09

vikram k


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 named runBare(), which is a method provided by ConditionalTestCase and JUnit TestCase class.

So you have 2 solutions:

  • Use the AlexR answer to use JUnit 4 tests and Spring;
  • Keep your inheritance of AbstractTransactionalDataSourceSpringContextTests, but use the onSetUp and onTearDown methods instead of the @Before and @After methods.
like image 29
Romain Linsolas Avatar answered Sep 22 '22 01:09

Romain Linsolas