加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么不使用伪随机数生成器来生成测试数据?

发布时间:2020-12-15 04:13:38 所属栏目:Java 来源:网络整理
导读:从书籍 Java Concurrency in Practice,第12.1章测试正确性,特别是12.1.3测试安全性(作者想要设置测试用例来测试有界缓冲类的数据 – 种族安全性) To ensure that your test actually tests what you think it does,it is important that the checksums thems
从书籍 Java Concurrency in Practice,第12.1章测试正确性,特别是12.1.3测试安全性(作者想要设置测试用例来测试有界缓冲类的数据 – 种族安全性)

To ensure that your test actually tests what you think it does,it is
important that the checksums themselves not be guessable by the
compiler. It would be a bad idea to use consecutive integers as your
test data because then the result would always be the same,and smart
compiler could conceivably just precompute it.

To avoid this problem,test data should be generated randomly,but many
otherwise effective tests are compromised by a poor choice of random
number generator(RNG). Random number generation can create couplings
between classes and timing artifacts because most random number
generator classes are thread safe and therefore introduce additional
synchronization.Giving each thread its own RNG allows a
non-thread-safe RNG to be used.

我不明白作者反对使用随机数生成器生成测试输入的观点.特别是行随机数生成可以创建类之间的耦合,并且我不清楚时序伪像.

>他指的是哪些类和时间工件?
> RNG可以创造什么样的联轴器?

解决方法

Random number generation can create couplings between classes and timing artifacts is not clear to me.

考虑到下一句话,这一点就更清楚了:

because most random number generator classes are thread safe and therefore introduce additional synchronization

内存同步可能会改变程序的时间.如果您查看Random,您可以看到它使用了AtomicInteger,因此使用它会导致读写内存障碍,因为测试数据的生成可能会改变其他线程看到数据的方式和时间.整体应用.

Which classes and timing artifacts is he referring to here?

任何使用线程并依赖于内存同步的类都可能会受到影响.基本上他们调用的所有线程和类.

What kind of couplings the RNG can create?

正如蜥蜴@Bill评论的那样,本书说通过使用RNG,程序的时间依赖于RNG同步或受其影响.

这里真正的教训是,如果可能的话,您注入程序的测试数据不应该改变程序的时间.它通常很难并且可能是不可能的,但目标是在测试中尽可能地模拟应用程序行为(时间,输入,输出……).

就解决方案而言,您可以使用另一个未同步的simple random algorithm.您还可以生成一个类,该类预先存储10000个随机数(或者您需要的多个),然后在没有同步的情况下将它们分发出去.但是通过在测试中使用类进行内存同步,您正在改变程序的时间.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读