This is my 1st post!
I would like to use both assertTrue(boolean)
and assertFalse(boolean)
in the same test using JUnit4. I am using Parameterization, so I would like to include parameters that will fail the test, to verify that they do infact fail.
The method that I am testing accepts a String, checks if the string is in an acceptable currency format (numbers only, no letters, max 2 digits after a decimal point), and returns a HashMap with 2 keys: VALID which is a boolean denoting the strings validity as a currency, and FORMATTING which is a String added to the original valid String to ensure all valid Strings end up with a decimal point and exactly 2 digits thereafter. Invalid strings will not be formatted.
Here is my code:
@RunWith(value = Parameterized.class)
public class CheckCurrencyFormatTest {
private String input;
private String output;
@Parameters
public static Collection<String[]> data() {
String[][] data = {
{"1", "1.00"} //return true
,{"1.", "1.00"} //return true
,{"1.0", "1.00"} //return true
,{"1.00", "1.00"} //return true
//,{"1.000", "1.000"} //return false
//,{"m","m"} //return false
};
return Arrays.asList(data);
}
public CheckCurrencyFormatTest( String input, String output) {
this.input = input;
this.output = output;
}
@Test
public void testCheckString() {
CheckCurrencyFormat ccf = new CheckCurrencyFormat();
HashMap hm;
boolean valid;
String resultString;
valid = false;
resultString = "";
hm = ccf.checkString(input);
for (Object key : hm.keySet()) {
if ("VALID".equals(key.toString())){
valid = Boolean.parseBoolean(hm.get(key).toString());
}
if ("FORMATTING".equals(key.toString())){
System.out.println(input + " and add " + hm.get(key).toString());
resultString = input+(hm.get(key).toString());
}
}
assertTrue(valid);
//assertFalse(valid);
assertEquals(output, resultString);
}
The tests run successfully with the following lines commented out: ,{"1.000", "1.000"}
and ,{"m","m"}
and assertFalse(valid);
Thank you kindly.
Add an "expected result" field
private String input;
private String output;
private boolean expectedResult;
@Parameters
public static Collection<Object[]> data() {
Object[][] data = {
{"1", "1.00", true} //return true
,{"1.", "1.00", true} //return true
,{"1.0", "1.00", true} //return true
,{"1.00", "1.00", true} //return true
,{"1.000", "1.000", false} //return false
,{"m","m", false} //return false
};
return Arrays.asList(data);
}
And in the test method :
assertTrue(valid == expectedResult);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.