@After ,@before 不在测试用例中工作

新手上路,请多包涵

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在控制台上

但是,如果我删除 @After@Before 它运行@Test。我的代码在这里:

 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");
    }
}

为什么不 @After , @Test@before 同时工作?

原文由 abhishek ameta 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 446
2 个回答

AbstractTransactionalDataSourceSpringContextTests 类强制使用旧的 JUnit 3.x 语法,这意味着任何 JUnit 4 注释都不起作用。

Your method runBare() is executed not because of the @Before annotation, but because it is named runBare() , which is a method provided by ConditionalTestCase 和 JUnit TestCase 类。

所以你有2个解决方案:

  • 使用 AlexR 答案来使用 JUnit 4 测试和 Spring;
  • Keep your inheritance of AbstractTransactionalDataSourceSpringContextTests , but use the onSetUp and onTearDown methods instead of the @Before and @After methods .

原文由 Romain Linsolas 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 @BeforeEach 代替 @Before@AfterEach 代替 @After

原文由 vikram k 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题