我有两个JUnit4测试类,说MyTest1,MyTest2各有几个测试方法。 实际上这些是Selenium JUnit TestCases。
在MyTest1.someMethodInsertingDate()中,我会将一些数据插入到数据库中,并且需要一些时间来处理。
在MyTest2.validateProcessedData()中,我需要验证第一个测试方法中插入的已处理数据是否有效。
我知道测试方法/案例之间的耦合不是一个好习惯。但我正在编写SeleniumTests来自动化UI上的用户操作,所以我必须这样做。
我正在使用MyTestSuite和@RunWith&执行这两个TestCase。 @SuiteClasses。
现在我怎么能告诉JUnit执行MyTest2 TestCase有一些延迟,比如1分钟。
答案 0 :(得分:2)
我认为你没有得到这个问题的答案(至少不是你想要的答案),因为在测试套件中依赖这些机制通常被认为是不好的做法。如果你有这些类型的依赖,你的测试将变得非常难以维护,并且(很可能会)导致你以后难以调试它们。
您可以抽象出第一个测试,第二个测试也许可以扩展它。然后,第二个测试将使用其设置中的通用功能(可能具有不同的数据)。这应该允许您同时运行测试,因为每个测试都是原子实体。
答案 1 :(得分:1)
我们希望所有人都认为这是不好的做法,但也有例外。 说明一点,我们不是在讨论单元测试,而是集成测试(JUnit可能不适合这项工作,但我没有找到更好的工具)
我也在做Selenium测试。我对第三方测试服务器进行集成测试,如果我在没有sleep()的情况下运行测试,那么这种行为是随机的。
这是可能的解决方案之一,请注意,这只是通过运行一次来测试:
public class SleepySuite extends Suite {
private final Logger log = LoggerFactory.getLogger(SleepySuite.class);
private final Integer defaultSleepSec = 0;
private final Integer sleepSec;
public SleepySuite(Class<?> klass, RunnerBuilder builder) throws InitializationError {
super(klass, builder);
sleepSec = initSleep(klass);
}
private Integer initSleep(Class<?> klass) {
SleepSec ts = klass.getAnnotation(SleepSec.class);
Integer sleep = defaultSleepSec;
if (ts != null) {
sleep = ts.value();
log.debug("Configured with sleep time: {}s", sleep);
}
return sleep;
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface SleepSec {
public int value();
}
/**
* @see org.junit.runners.Suite#runChild(org.junit.runner.Runner, org.junit.runner.notification.RunNotifier)
*/
@Override
protected void runChild(Runner runner, RunNotifier notifier) {
super.runChild(runner, notifier);
//Simply wrapped Thread.sleep(long)
TestUtils.sleep(sleepSec);
}
}
你的套房:
@RunWith(SleepySuite.class)
@Suite.SuiteClasses({
Some.class,
SomeOther.class
})
@SleepySuite.TimeoutSec(30)
public class YourSuite{
}
答案 2 :(得分:1)
你可以使用简单的&#34; @ Before&#34;注解。 它应该在每次启动测试时延迟执行线程。
示例:
@Before
public void initialise() throws InterruptedException {
Thread.sleep(2000);
}
答案 3 :(得分:0)
您可以通过在每个测试方法的末尾添加内容来使脚本休眠 在PHP中:
sleep(60);
答案 4 :(得分:0)
在数据库代码之后的第一个测试用例中,您可以在Java中引发一些等待:
long end3 = System.currentTimeMillis()+ 6000;
while(System.currentTimeMillis()<end3)
{
// Do nothing here Just time pass.
}
这将确保Java代码在DB代码之后等待6000毫秒,并且应该足以添加数据。您可以根据数据大小调整时间。
答案 5 :(得分:0)
后代共享,
像Thread#sleep
这样的静态代码分析工具始终不鼓励在JUnit测试中使用sonarqube
。与其使用上述方法,不如使用Awaitility
之类的某些库。尽管这不是理想的解决方案,但它比使用Thread#sleep
更好。
所需的代码更改:
testImplementation('org.awaitility:awaitility:4.0.3')
将以下代码片段放在需要延迟的地方。在以下示例中,我将延迟持续时间设置为一秒。从概念上讲,这将执行与Thread.sleep(1000)
Awaitility.await().pollDelay(Durations.ONE_SECOND).until(() -> true);