gpt4 book ai didi

java - 具有执行器的 JUnit 服务类立即返回控制权

转载 作者:行者123 更新时间:2023-11-30 03:17:31 24 4
gpt4 key购买 nike

我有下一个服务级别:

    public class JDBCServiceImpl {
//////
public void writeTablesColumnsToFiles(DataSource dataSource, List<Table> tableInfos) {
ExecutorService executor = Executors.newFixedThreadPool(2);
for (Table table : tableInfos) {
Runnable worker = new Runnable() {
@Override
public void run() {
try {
writeTableColumnsToFiles(dataSource, table);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
executor.execute(worker);
}
executor.shutdown();
}

//////
public void writeTableColumnsToFiles(DataSource dataSource, Table tableInfo) {
//
try (Connection connection = dataSource.getConnection()) {
.....
}
}
}

我想在 JUnit 类中测试此服务:

public class JDBCLoaderServiceImpl {
@Test
public void testExecutingOfJDBCService() {
.....
JDBCServiceImpl jdbcLoaderService = new JDBCServiceImpl();
jdbcLoaderService.writeTablesColumnsToFiles(dataSource, allTables);
}
}

JUnit 在执行程序完成任务时不等待的主要问题(在 Debug模式下,我看到在此代码之后 try (Connection connection = dataSource.getConnection()) 服务类返回控制) 。那么如何解决这个问题呢?提前致谢。

最佳答案

我建议测试writeTableColumnsToFiles(DataSource dataSource, Table tableInfo)并忽略与线程一起使用的方法。

但是如果您确实想测试它,您可以模拟 ExecutorService 并在单线程中完成所有工作。

关于java - 具有执行器的 JUnit 服务类立即返回控制权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32225365/

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