【发布时间】:2019-09-22 11:41:35
【问题描述】:
我正在尝试为具有两个重载方法的类编写 junit 测试。这是我的测试代码
public class Solution {
public static String getDurationString(int minute, int seconds) {
if (minute < 0) {
return "Invalid Value";
} else if (seconds < 0 || seconds > 59) {
return "Invalid Value";
} else {
int hours = minute / 60;
minute %= 60;
return getTimeString(hours) + "h " + getTimeString(minute) + "m " + seconds + "s";
}
}
public static String getDurationString(int seconds) {
if (seconds < 0) {
return "Invalid Value";
}
int minutes = seconds / 60;
seconds %= 60;
int hours = minutes / 60;
minutes %= 60;
return getTimeString(hours) + "h " + getTimeString(minutes) + "m " + seconds + "s";
}
//returns value in xx format
private static String getTimeString(int val) {
if (val < 10) {
return "0" + val;
}
return "" + val;
}
}
我能够使用 JUnit 的 Parameterized Runner 使用一些数据来测试 getDurationString(min,sec) 函数。我想使用相同的测试代码为 getDurationString(sec) 函数编写测试,但我不知道该怎么做。我看了一些stackoverflow question,但没有帮助(可能是因为我使用的是 JUnit4)。
知道如何使用 JUnit4 实现这一点吗?
更新:添加测试代码供参考
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
class SolutionTest {
@Parameterized.Parameters(name = "Test{index} -> {0} min {1} sec returns {2}")
public static Iterable<Object[]> dataForTwoParameterMethod() {
return Arrays.asList(new Object[][]{
{-1, 10, "Invalid Value"}, //minutes < 0 returns "Invalid value"
{1, -1, "Invalid Value"}, //Negative seconds value
{61, 50, "01h 01m 50s"}, //valid value returns time in format "XXh YYm ZZs"
});
}
int minute;
int seconds;
String durationString;
public SolutionTest(int minute, int seconds, String durationString) {
this.minute = minute;
this.seconds = seconds;
this.durationString = durationString;
}
@Test
public void getDurationString() {
assertEquals(durationString, Solution.getDurationString(minute, seconds));
}
@Test @Ignore("TODO: Not able to find a way to inject two different data into one JUnit Test")
public void testGetDurationString() {
//TODO: how to use two data in single data driven test
}
}
【问题讨论】:
-
能否请您展示您已经尝试过的内容?特别是,您对
getDurationString(min,sec)的工作测试看起来如何,您是如何尝试编写其他测试的? -
@DirkHerrmann 添加了有问题的测试代码。
标签: java unit-testing junit tdd junit4