@After,@之前没有在testcase中工作
我已经开始测试了,现在我想使用@Before
, @Before
和@Test
但我的应用程序只运行@Before
方法并在控制台上输出
之前
但是,如果我删除@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"); } }
@before
, @before
和@before
为什么不同时工作?
AbstractTransactionalDataSourceSpringContextTests
类强制使用旧的JUnit 3.x语法,这意味着任何JUnit 4注释都不起作用。
您的方法runBare()
的执行不是因为@Before
注释,而是因为它被命名为runBare()
,这是由ConditionalTestCase
和JUnit TestCase
类提供的方法。
所以你有2个解决方案:
- 使用AlexR答案使用JUnit 4测试和Spring;
- 保留
AbstractTransactionalDataSourceSpringContextTests
的inheritance,但使用onSetUp
和onTearDown
方法而不是@Before
和@After
方法。
它应该工作……但是因为你正在使用spring框架并且几年前推出了JUnit 4,我建议你使用注释而不是inheritance。
因此,使用@RunWith(SpringJUnit4ClassRunner.class)
注释您的类。 删除extends AbstractTransactionalDataSourceSpringContextTests
。
不要忘记将@Before和@After方法设为 静态
现在它应该工作。
即使你想扩展Spring抽象测试类,至少要注意其中一些被弃用。 例如,不建议使用AbstractTransactionalDataSourceSpringContextTests
类。
使用@BeforeEach
代替@Before
和@AfterEach
而不是@After
。