gpt4 book ai didi

java - 复杂枚举的联合测试

转载 作者:行者123 更新时间:2023-11-30 03:13:05 26 4
gpt4 key购买 nike

我有一个可以以多种不同方式呈现的枚举。作为字符串、作为整数、作为 double (不同范围)、作为 Vector2D,最后作为枚举值本身。这是一个通用示例,这些值不具有代表性。我的实际使用有更多的值(value)和方法。

 public enum Example {

value0("Name0", 0, 0.0, 0.01707, 0.12534);
value1("Name1", 1, 25.0, 0.1707, 0.53434);
value2("Name2", 2, 55.0, 0.70701, 0.23534);
value3("Name3", 3, 65.0, 0.01707, 0.34786);
value5("Name4", 4, 100.0, 0.01707, 0.42594);

private final String name;
private final int number;
private final double head;
private final Vector2d pointVec;

/**
* Constructor invoked for each value above.
*/
enumExample(String name, int no, double hdg, float compX, float CompY) {
this.name = name;
this.number = no;
this.head = hdg;
this.pointVec = new Vector2d(compX, compY);
}

public String getName(){
return name;
}

public int getNumber() {
return no;
}

public int getHead() {
return head;
}

public Vector2D getVector() {
return pointVec;
}

public Example getCalcValue(int value) {
return calcValue(getNumber(value));
}

/*
* There are more methods that perform calculations on the enum's
* attributes.
*/
}

为了确保使用此枚举的其他类能够使用正确的功能枚举。我希望对其进行一套全面的测试,从而确保数据输入正确执行,并且枚举及其关联数据没有损坏。

目前,具有 5 个枚举值的示例有 31 个测试。我需要最多 33 个枚举值的版本。大约有 200 次测试。

我希望能够使用数据驱动测试,因为这将使肉眼检查测试数据变得更容易。

有人对如何将其设置为枚举有任何想法吗?我发现的所有数据驱动测试示例都有一个简单的类和一种测试方法。

最佳答案

Parameterized tests并不是每一个设想的最漂亮的代码片段(我不喜欢整个 object[] 东西​​),但你可能可以使用它们来做你的事情......在这个例子中,我有两个测试,结果符合预期,但是当然,您可以为多个测试添加许多参数,每个测试都测试枚举的特定部分。

@RunWith(Parameterized.class)
public class SomeTest {

@Parameters
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] {
{ MyEnum.Value1, 0, "x" },
{ MyEnum.Value2, 1, null },
{ MyEnum.Value3, 127, "y" },
etc.
});
}

private MyEnum enumValue;
private int expectedInt;
private String expectedString;

// Each test set will get one set of parameters from your array
public SomeTest(MyEnum enumValue, int expectedInt, String expectedString) {
this.enumValue = enumValue;
this.expectedInt = expectedInt;
this.expectedString = expectedString;
}

@Test
public void testInt() {
// do whatever calculation you need to do on the data
int result = this.enumValue.doSomething() * 2 - 100;
assertEquals(expectedInt, result);
}

@Test
public void testString() {
// do whatever calculation you need to do on the data
String result = this.enumValue.doSomethingElse().substring(2,5);
assertEquals(expectedString, result);
}
}

这样,您只需为枚举本身编写一组测试,然后使用实际枚举值和这些值的预期结果对它们进行参数化。

我建议在测试类中进行实际计算,而不仅仅是检查值,因为检查值会导致人们将它们复制并粘贴到您的测试中,这对任何人都没有帮助。

关于java - 复杂枚举的联合测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33230813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com