gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:10:04 26 4
gpt4 key购买 nike

背景/场景:

我正在使用 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 更好的替代方案吗?

最佳答案

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

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

为此,您可能必须从 junit API 重写 RunListener 中的方法

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

关于java - 使用 TestWatcher 记录测试用例中的断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31959039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com