Java 如何创建一个在数据库中等待记录出现的测试?
我有一个方法,它在另一个线程中开始生成一些报告,而主线程返回一个指向谷歌文件夹的链接,在那里创建的报告应该上传。创建报告后,它会在数据库中插入一条包含一些信息的记录Java 如何创建一个在数据库中等待记录出现的测试?,java,multithreading,testing,Java,Multithreading,Testing,我有一个方法,它在另一个线程中开始生成一些报告,而主线程返回一个指向谷歌文件夹的链接,在那里创建的报告应该上传。创建报告后,它会在数据库中插入一条包含一些信息的记录 public Link startReportCreation(ReportRequest reportRequest) { Link link = /** some logic **/; taskExecutor.execute(() -> { /** report creation logi
public Link startReportCreation(ReportRequest reportRequest) {
Link link = /** some logic **/;
taskExecutor.execute(() -> {
/** report creation logic **/
});
return link;
那么,在不修改startReportCreation
方法的情况下,测试插入记录信息的最佳方法是什么
更新 目前我有
while(taskExecutor.getActiveCount()!=0)
锁的种类,表示taskExecutor
已结束执行,我可以检查数据库。但我认为有更好的方法
顺便说一句,sry具有误导性,这不是单元测试,它只是在真实数据上手动测试方法的执行者
已解决 因此,我成功地重构了我的
startReportCreation
方法,而不是简单的taskExecutor
,我使用了CompletableFuture
,所以现在看起来是这样的:
public CompletableFuture<Link> startReportCreation(ReportRequest reportRequest) {
/** some logic **/
return CompletableFuture.supplyAsync(() -> {
Link link = /** some logic **/;
return link;
}, taskExecutor);
}
public CompletableFuture startreport创建(ReportRequest ReportRequest){
/**一些逻辑**/
返回CompletableFuture.SupplySync(()->{
Link Link=/**一些逻辑**/;
返回链接;
},任务执行人);
}
因此,在生产代码中,我使用
CompletableFuture.getNow()
方法,在测试中,我使用CompletableFuture.get()
等待报告的创建。首先记住单元测试的基本原则。
F:快
I:独立
R:可重复
S:小的
T:及时
下面是一个详细回顾它们的链接:
为了达到您的需要,您必须以以下方式准备测试:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ReportGeneratorTest {
//This is executed before each @Test, generally is used for prepare the ambient, instantiate services, start servers and so on.
@Before
public void setUp() throws IOException {
report = MyReportService.createReport();
}
//This is executed after each @Test generally this used for tear down your servers or data bases, or delete all the records inserted
@After
public void tearDown() {
MyReportService.deleteById(10);
}
@Test
public void verifyInsertion() throws Exception {
//Here you can verify that the record of your serive or logic it's ok
assertTrue(MyReportService.getLastId() > 10); //Or whatever
}
}
编辑:
从并发单元的文档中:
您可以创建一个线程并等待它
@Test
public class WaiterTest {
@Test
public void shouldSupportMultipleThreads() throws Throwable {
final Waiter waiter = new Waiter();
for (int i = 0; i < 5; i++)
new Thread(new Runnable() {
public void run() {
waiter.assertTrue(true);
waiter.resume();
}
}).start();
waiter.await(0);
}
@测试
公务舱服务员考试{
@试验
public void应该支持multipleThreads()抛出可丢弃的{
最终服务员=新服务员();
对于(int i=0;i<5;i++)
新线程(newrunnable()){
公开募捐{
服务员:资产真(真);
服务员:简历;
}
}).start();
服务员。等待(0);
}
这在我的示例中不起作用,因为createReport()
方法将在另一个线程中开始创建报告,而verifyInsertion
将不会在数据库中看到任何更改。我明白了,也许这种方法可以帮助您:但我不想在我的代码中插入那些waiter
,只是为了测试它(我看不出有人会使用它)。是的,我想我的要求太高了,似乎我需要重新构造代码以正确测试它。无论如何,感谢您的链接,这对CompletionService
非常有帮助。