Junit快速检查:产生符合样式的字串

pu3pd22g  于 2022-11-11  发布在  其他
关注(0)|答案(3)|浏览(249)

我正在使用pholser的端口。我必须生成匹配给定模式的字符串,如\[a-zA-Z0-9\\.\\-\\\\;\\:\\_\\@\\[\\]\\^/\\|\\}\\{]* Length 40
我将Generator类扩展为:

public class InputGenerator extends Generator<TestData> {...}

它会多载函数:

publicTestData generate(SourceOfRandomness random, GenerationStatus status) {...}

现在,random有类似**nextDouble(),nextInt()**的函数,但是没有字符串的函数!我如何生成符合上述模式的随机字符串?

mlnl4t2r

mlnl4t2r1#

下面是一个自定义生成器的代码段,它实现了generate(..)方法,以返回与您发布的模式匹配的随机字符串。

public class MyCharacterGenerator extends Generator<String> {

    private static final String LOWERCASE_CHARS = "abcdefghijklmnopqrstuvwxyz";
    private static final String UPPERCASE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String NUMBERS = "0123456789";
    private static final String SPECIAL_CHARS = ".-\\;:_@[]^/|}{";
    private static final String ALL_MY_CHARS = LOWERCASE_CHARS
            + UPPERCASE_CHARS + NUMBERS + SPECIAL_CHARS;
    public static final int CAPACITY = 40;

    public MyCharacterGenerator () {
        super(String.class);
    }

    @Override
    public String generate(SourceOfRandomness random, GenerationStatus status) {
        StringBuilder sb = new StringBuilder(CAPACITY);
        for (int i = 0; i < CAPACITY; i++) {
            int randomIndex = random.nextInt(ALL_MY_CHARS.length());
            sb.append(ALL_MY_CHARS.charAt(randomIndex));
        }
        return sb.toString();
    }
}

edit一个简单的单元测试,用于演示MyCharacterGenerator类的用法。

import com.pholser.junit.quickcheck.ForAll;
import com.pholser.junit.quickcheck.From;
import static org.junit.Assert.assertTrue;
import org.junit.contrib.theories.Theories;
import org.junit.contrib.theories.Theory;
import org.junit.runner.RunWith;

@RunWith(Theories.class)
public class MyCharacterGeneratorTest {

    @Theory
    public void shouldHold(@ForAll @From(MyCharacterGenerator.class) String s) {
        // here you should add your unit test which uses the generated output
        // 
        // assertTrue(doMyUnitTest(s) == expectedResult);

        // the below lines only for demonstration and currently
        // check that the generated random has the expected
        // length and matches the expected pattern
        System.out.println("shouldHold(): " + s);
        assertTrue(s.length() == MyCharacterGenerator.CAPACITY);
        assertTrue(s.matches("[a-zA-Z0-9.\\-\\\\;:_@\\[\\]^/|}{]*"));
    }
}

样本输出shouldHold生成

shouldHold(): MD}o/LAkW/hbJVWPGdI;:RHpwo_T.lGs^DOFwu2.
shouldHold(): IT_O{8Umhkz{@PY:pmK6}Cb[Wc19GqGZjWVa@4li
shouldHold(): KQwpEz.CW28vy_/WJR3Lx2.tRC6uLIjOTQtYP/VR
shouldHold(): pc2_T4hLdZpK78UfcVmU\RTe9WaJBSGJ}5v@z[Z\
...
pdtvr36n

pdtvr36n2#

没有random.nextString(),但是在junit-quickcheck-generators库中有一种生成随机字符串的方法。你可以在使用gen().type(String.class)创建新的生成器时访问它。但是,我们似乎没有太多的控制权。
下面是一个简单的StringBuilder生成器示例,用于演示如何使用String生成器:

import com.pholser.junit.quickcheck.generator.GenerationStatus;
import com.pholser.junit.quickcheck.generator.Generator;
import com.pholser.junit.quickcheck.random.SourceOfRandomness;

public class StringBuilderGenerator extends Generator<StringBuilder> {

    public StringBuilderGenerator() {
        super(StringBuilder.class);
    }

    @Override
    public StringBuilder generate(SourceOfRandomness random, GenerationStatus status) {
        String s = gen().type(String.class).generate(random, status);
        return new StringBuilder(s);
    }
}
r9f1avp5

r9f1avp53#

我刚刚创建了一个库,它假定以一种通用方式完成您想要的任务:https://github.com/SimY4/coregex
简单用法示例:

import com.pholser.junit.quickcheck.Property;
import com.pholser.junit.quickcheck.runner.JUnitQuickcheck;
import org.junit.runner.RunWith;

import java.util.UUID;

import static org.junit.Assert.assertEquals;

@RunWith(JUnitQuickcheck.class)
public class CoregexGeneratorTest {
  @Property
  public void shouldGenerateMatchingUUIDString(
      @Regex("[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}")
          String uuid) {
    assertEquals(uuid, UUID.fromString(uuid).toString());
  }
}

相关问题