@After ,@before not working in testcase

前端 未结 5 908
遇见更好的自我
遇见更好的自我 2020-12-17 09:15

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

相关标签:
5条回答
  • 2020-12-17 09:18

    Check that you are using Junit4 because from Junit5 onwards @Before/@After is now @BeforeEach/@AfterEach and similalry @BeforeClass/@AfterClass is @AfterAll/@BeforeAll.

    0 讨论(0)
  • 2020-12-17 09:28

    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). Remove extends 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.

    0 讨论(0)
  • 2020-12-17 09:29

    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.
    0 讨论(0)
  • 2020-12-17 09:33

    in my case, I had that problem the solution was to change the java access modifier, It was way private.

    before (not working) @Test void validate() throws Exception {}

    after (working) @Test public void validate() throws Exception {}

    0 讨论(0)
  • 2020-12-17 09:43

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

    0 讨论(0)
提交回复
热议问题