![](/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.