Home

JUnit 4

qianmoQqianmoQ· 更新于 2026-10-13· 阅读 3 分钟· 0 次阅读

登录后可跨设备保存划线和私人笔记登录

JUnit 4

@Rule/@ClassRule integration

JUnit4 @Rule/@ClassRule : This mode starts the container before your tests and tears it down afterwards.

Add a @Rule or @ClassRule annotated field to your test class, e.g.:

public class SimpleMySQLTest {
    @Rule
    public MySQLContainer mysql = new MySQLContainer();

    // [...]
}

Manually controlling container lifecycle

As an alternative, you can manually start the container in a @BeforeClass/@Before annotated method in your tests. Tear down will be done automatically on JVM exit, but you can of course also use an @AfterClass/@After annotated method to manually call the stop() method on your container.

Example of starting a container in a @Before annotated method:

class SimpleMySQLTest {
    private MySQLContainer mysql = new MySQLContainer();

    @Before
    void before() {
        mysql.start();
    }

    @After
    void after() {
        mysql.stop();
    }

    // [...]
}

Singleton containers

Note that the singleton container pattern is also an option when using JUnit 4.

评论

登录后参与评论

正在加载评论…