使用TestWatcher记录测试用例中的断言失败

时间:2015-08-12 07:46:10

标签: java unit-testing junit log4j

上下文/场景:

我正在使用JUnit和Apache Log4J来学习TDD和日志服务最佳实践。我有一个GenericTaskInterpreter类,它有一个方法connectToMySQL,它将尝试连接到MySQL数据库并返回java.sql.Connection类型的对象。

class GenericTaskInterpreter {

    /**
    * This method will attempt to connect to a MySQL database
    * and return an object of type java.sql.Connection
    */
    public Connection connectToMySQL() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/TestDatabase", "root",
            "password");
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
}

我有一个班级GenericTaskInterpreterTests,我已经为这个方法(以及其他方法)编写了测试用例。

public class GenericTaskInterpreterTests extends TestCase {

    private static final GenericTaskInterpreter genericTaskInterpreter = new GenericTaskInterpreter();

    private static final Logger logger = LogManager.getLogger(GenericTaskInterpreterTests.class);

    private static boolean setUpIsDone = false;

    private static boolean tearDownIsDone = false;

    private static FileAppender fileAppender;

    @Rule
    public TestRule watchman = new TestWatcher() {

        private String watchedLog;

        // Overridden methods apply, succeeded, skipped, starting and finished....

    };

    protected void setUp() throws Exception {
        if (setUpIsDone) {
            return;
        }
        // Do the setup.
        fileAppender = new FileAppender();
        fileAppender.setName("FileLogger");
        fileAppender.setFile("/path/to/log4j-application.log");
        fileAppender.setLayout(new PatternLayout("%d %-5p [%c{1}.%M] %m%n"));
        fileAppender.setThreshold(Level.DEBUG);
        fileAppender.setAppend(true);
        fileAppender.activateOptions();

        LogManager.getRootLogger().addAppender(fileAppender);
        setUpIsDone = true;
        //logger.info("####### All configurations complete... #######");
        logger.info("####### Starting test cases... #######");

    }

    protected void tearDown() throws Exception {

        if (tearDownIsDone) {
            return;
        }
        // Do the teardown.
        //fileAppender.close();
        LogManager.getRootLogger().removeAppender(fileAppender);
        tearDownIsDone = true;   
    }

    public void testconnectToMySQLIfConnectionObjectIsNotNull() {
        assertNotNull(genericTaskInterpreter.connectToMySQL());
    }
}

问题:

  • 如何在此测试用例场景中使用TestWatcher记录断言失败?
  • 有没有比使用TestWatcher更好的选择?

2 个答案:

答案 0 :(得分:2)

当任何事件(设置,测试,清理失败/通过/跳过)发生时,您可能希望附加公共/离散结果文件。

如果您并行运行测试,则必须将日志记录写入同步到结果文件

要执行此操作,您可能必须从junit API

覆盖RunListener中的方法 RunListener类的

http://junit.sourceforge.net/javadoc/org/junit/runner/notification/RunListener.html

答案 1 :(得分:1)

@Rule
public TestRule watchman = new TestWatcher() {

    @Override
    protected void succeeded(final Description description) {
        logger.info(String.format("Success: %s", description));
    }

    @Override
    protected void failed(final Throwable e, final Description description) {
        logger.info(String.format("Failed: %s", description), e);
    }

    @Override
    protected void starting(final Description description) {
        logger.info(String.format("Starting: %s", description));
    }

    @Override
    protected void finished(final Description description) {
        logger.info(String.format("Finished: %s", description));
    }

    };

如果你想在某个地方写它,Log4J会做得很好,就像你已经做的那样。就个人而言,我会通过文件配置它,而不是使用根记录器,但这只是一个细节。