import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ArgsTest {
String argsStr3 = "-l -p 8080 -d /usr/logs";
String argsStr2 = "-p 8080 -d /usr/logs";
Args argsThree = new Args(argsStr3);
Args argsTwo = new Args(argsStr2);
@Test
void should_return_args_count() {
assertEquals(3, argsThree.argsCount());
assertEquals(2, argsTwo.argsCount());
}
@Test
void should_return_args_pair() {
assertEquals(3, argsThree.pair.size());
assertEquals(2, argsTwo.pair.size());
}
@Test
void should_return_default_true_if_input_l_but_no_value() {
assertEquals(true, argsThree.get("log"));
}
}
import java.util.HashMap;
public class Args {
private String argsStr;
public HashMap<String, String> pair;
public Args(String argsStr) {
pair = new HashMap<>();
this.argsStr = argsStr;
getArgsPair();
}
public int argsCount() {
return pair.size();
}
public void getArgsPair() {
String[] argsList = argsStr.split(" ");
for (int i = 0; i < argsList.length; i++) {
if (argsList[i].startsWith("-")) {
if (!argsList[i+1].startsWith("-")) {
pair.put(argsList[i], argsList[i + 1]);
i += 1;
} else {
pair.put(argsList[i], "");
}
}
}
}
public boolean get(String item) {
System.out.println("PAIR" + pair);
if (item.equals("log")) {
if (pair.containsKey("-l") && pair.get("-l").isEmpty()) {
return true;
}
}
return false;
}
}
评论