【发布时间】:2020-03-07 00:51:04
【问题描述】:
我正在并行运行我的测试用例。很多时候,我在从反应下拉列表中选择值时遇到问题。假设,我必须从反应下拉列表中选择一个值,我必须执行 2 个操作:
1. 点击下拉按钮。
2. 从下拉列表中选择值。
有时,在并行执行期间,执行完第一步后,下一个线程正在运行,因此窗口会被切换。当它切换回第一个窗口并执行第二步时,下拉菜单不再存在,因此测试用例失败。
下拉菜单如下所示:
无论如何我会让其他线程等待一段时间,直到该线程执行操作?
我尝试了什么?
尝试 1:
他们说在许多地方,我们不能暂停另一个线程的线程。但是,我仍然尝试了这个。所有 TestNG 线程的名称似乎都包含“TestNG”,所以我用它来识别它。然后又加了一个条件,如果这个线程的id和我的线程id不一样,我可以让它等待。
public void stopThisThread(long threadId) throws Throwable{
synchronized(this) {
System.out.println("Stop other threads called...");
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
try {
for(Thread t : threadSet) {
System.out.println("Inside loop : " + printThread(t));
if(t.getName().contains("TestNG") && t.getId()!=threadId) {
t.wait();
System.out.println("Wait is called on " + t.getId());
}
}
}catch(Throwable t) {
t.printStackTrace();
}
}
}
正如预期的那样,它没有工作。它抛出了java.lang.IllegalMonitorStateException
试试 2
我想,与其从另一个线程调用等待,不如从同一个线程调用等待,然后让它恢复操作。所以,这里 test2 将从下拉列表中选择值。所以,我让 test1 线程等待。一旦 test2 完成了这项工作,我想调用“通知”以使 test1 恢复其操作。它也没有工作。
@Test
public synchronized void test1() throws Throwable {
System.out.println("test1 - " + printThread(Thread.currentThread()));
int i = 0;
while(true) {
System.out.println("test1");
if(i == 0)
Thread.currentThread().wait();
Thread.sleep(2000);
}
}
@Test
public synchronized void test2() throws Exception{
System.out.println("test2 - " + printThread(Thread.currentThread()));
int i = 0;
while(true) {
System.out.println("test2");
Thread.sleep(2000);
if(++i == 5)
Thread.currentThread().notifyAll();
}
}
这会在两个测试用例上抛出java.lang.IllegalMonitorStateException。
谁能帮我解决这个问题?
【问题讨论】:
标签: java multithreading selenium selenium-webdriver testng