![](/img/trans.png)
[英]How to test only the “key” from .properties file in java using Junit
[英]how to test parameters using properties file in junit
我正在准备一个测试用例场景,在该场景中,将要针对它们的键进行测试的值放在properties
文件中。 我想如果所有键值都满足其对应值,则该方法应返回true,否则返回false。
下面是我的代码:
package mypackTest;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.is;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import static org.junit.Assert.assertThat;
@RunWith(Parameterized.class)
public class Test123 {
static Properties p = null;
private boolean expected;
@Parameters
public static List<String[]> data()
{
String[][] data = new String[][] { { "D:\\personal\\config.properties" }};
return Arrays.asList(data);
}
@BeforeClass
public static void setup()
{
p = new Properties();
try
{
//load a properties file
p.load(new FileReader(new File("D:\\personal\\config.properties")));
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
@Test
public void do_test() {
assertThat(TestThis.letstest(p.getProperty("abc1"), p.getProperty("abc2")), is(expected));
}
}
我要测试的课程:
package mypackTest;
public class TestThis {
public static boolean letstest(String abc1,String abc2){
if(abc1.equals("xyz1")&& abc2.equals("xyz2")){
return true;
}
return false;
}
}
属性文件
abc1=xyz1
abc2=xyz2
TestRunner类
package mypackTest;
import java.util.Enumeration;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import junit.framework.TestFailure;
import junit.framework.TestResult;
import junit.framework.TestSuite;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(CalculatorTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
我的输出低于
OUTPUT
do_test0:错误的参数数量
假
此代码存在各种问题。 首先:
private boolean expected;
您正在声明该字段-但您从未为其分配值。 因此,它被初始化为false
并保持false
。 因此,不要期望将它与true
事物进行比较会成功。
但除此之外:使用Parametrized
方式没有任何意义。 这个特殊运行器的思想是:@Parameters“ thing”包含多个值; 然后为每个条目循环调用您的测试。 那里只有一个文件名-就像“购买卡车然后运送一个手提箱的文件名”。 含义:您宁愿在此处指定键/值条目列表; 然后(例如)确保属性文件包含所有这些条目。 或类似的东西。
因此,真正的答案是:退后一步,了解基础知识。 例如,您对static的使用还意味着您不了解什么是static ,以及何时使用它。 然后遵循有关JUnit(普通JUnit)的教程。 当您确定如何正确使用它时,请阅读有关@Parametrized的教程。
换句话说:当您缺乏基本的了解时,请不要应用“试错法”。 仅当您有足够的经验而不总是立即为尝试的任何操作出错时,此策略才起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.