design patterns - Junit and java classes. -
design patterns - Junit and java classes. -
the below simple java class file checks if file provided user under home directory or not. throws exception when file not under home directory.
public class { public static void main(string args[]) { if (new a().processargs(args[0]) { throw exception("not under home directory"); } } // simple method check if file @ home directory private boolean processargs(string s) { file f = new file(s); string userhome = system.getproperty("user.home"); if (s.startswith(userhome) && f.exists() && additionallogic()) homecoming true; else homecoming false; } // additional business logic private boolean additionalbusinesslogic() { // wonderful things. } }
i want write simple junit test case testing java class. primary concern test additional business logic method. there way can bypass check directory must under user home directory.
i not comfortable in adding logic in main class create aware of junit classes. there improve way this?
while there's nil wrong fab's solution, decided write another:
public class main { public static void main(string args[]) { // todo: should check args length validator validator = new validator(); validator.validateargs(args[0]); } } public interface configuration { public string gethomedirectory(); } public class defaultconfiguration implements configuration { public string gethomedirectory() { string home = system.getproperty("user.home"); if (home == null) { throw new runtimeexception("user home directory not set!"); } homecoming home; } } public class validator { private configuration configuration; public validator() { this(new defaultconfiguration()); } public validator(configuration configuration) { this.configuration = configuration; } // simple method check if file @ home directory public void validateargs(string s) { file f = new file(s); if (!s.startswith(configuration.gethomedirectory()) || !f.exists() || !additionalbusinesslogic()) throw new runtimeexception("not under home directory!"); } // additional business logic private boolean additionalbusinesslogic() { // todo... homecoming true; } } public class validatortest { @test public void validatevalidargstest() { final string homedirectory = ".."; // todo string existingfile = homedirectory + ".."; // todo new validator(new configuration() { public string gethomedirectory() { homecoming homedirectory; } }).validateargs(existingfile); } @test(expected = runtimeexception.class) public void validateinvalidargstest() { string existingfile = ".."; // todo new validator(new configuration() { public string gethomedirectory() { homecoming "-invalid path-"; } }).validateargs(existingfile); } }
java design-patterns junit
Comments
Post a Comment