简体   繁体   English

生成大流以进行测试

[英]Generate a large stream for testing

We have a web service where we upload files and want to write an integration test for uploading a somewhat large file. 我们有一个Web服务,我们上传文件,并希望编写一个集成测试来上传一个稍大的文件。 The testing process needs to generate the file (I don't want to add some larger file to source control). 测试过程需要生成文件(我不想将更大的文件添加到源代码控制中)。

I'm looking to generate a stream of about 50 MB to upload. 我想要生成一个大约50 MB的流来上传。 The data itself does not much matter. 数据本身并不重要。 I tried this with an in-memory object and that was fairly easy, but I was running out of memory. 我用一个内存中的对象尝试了这个,这很容易,但我的内存不足。

The integration tests are written in Groovy, so we can use Groovy or Java APIs to generate the data. 集成测试是用Groovy编写的,因此我们可以使用Groovy或Java API生成数据。 How can we generate a random stream for uploading without keeping it in memory the whole time? 我们如何生成一个随机流进行上传而不是一直保存在内存中?

Here is a simple program which generates a 50 MB text file with random content. 这是一个简单的程序,它生成一个带有随机内容的50 MB文本文件。

import java.io.PrintWriter;
import java.util.Random;


public class Test004 {

    public static void main(String[] args) throws Exception {
        PrintWriter pw = new PrintWriter("c:/test123.txt");
        Random rnd = new Random();
        for (int i=0; i<50*1024*1024; i++){
            pw.write('a' + rnd.nextInt(10));
        }
        pw.flush();
        pw.close();
    }

}

You could construct a mock/dummy implementation of InputStream to supply random data, and then pass that in wherever your class/library/whatever is expecting an InputStream . 您可以构造一个InputStream的模拟/虚拟实现来提供随机数据,然后将它传递给您的类/库/任何期望InputStream

Something like this (untested): 像这样(未经测试):

class MyDummyInputStream extends InputStream {
    private Random rn = new Random(0);

    @Override
    public byte read() { return (byte)rn.nextInt(); }
}

Of course, if you need to know the data (for test comparison purposes), you'll either need to save this data somewhere, or you'll need to generate algorithmic data (ie a known pattern) rather than random data. 当然,如果您需要知道数据(用于测试比较目的),您需要将数据保存在某处,或者您需要生成算法数据(即已知模式)而不是随机数据。

(Of course, I'm sure you'll find existing frameworks that do all this kind of thing for you...) (当然,我相信你会发现现有的框架可以为你做所有这些事......)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM