In this post, I will talk about creating nicer syntax for verifications.
In Ruby, we can add new methods into existing class. Rspec adds some nice assert methods such as should_equal(expected_string) into string class. However, it is impossible to do it in Java. Right, we can’t do it in unit test. Fortunately, we are writing automated tests. we can control what to return. Hence, I write a wrap class to allow code to use rspec-like syntax.
public class TextDSL extends Assert {
private String text;
private String errorMessage;
public TextDSL(String text) {
this(text, "");
}
public TextDSL(String text, String errorMessage) {
this.text = text;
this.errorMessage = errorMessage;
}
public void shouldEqual(String expectedText) {
assertEquals(errorMessage, expectedText, text);
}
public void shouldNotEqual(String notExpectedText) {
assertFalse(errorMessage + " not expected:<" + notExpectedText + "> but was:<" + text + ">", notExpectedText.equals(text));
}
public void shouldEqual(int expectedInteger) {
assertEquals(errorMessage, String.valueOf(expectedInteger), text);
}
public void shouldNotEqual(int notExpectedInteger) {
assertFalse(errorMessage + " not expected:<" + notExpectedInteger + "> but was:<" + text + ">", String.valueOf(
notExpectedInteger).equals(text));
}
public void shouldInclude(String expectedIncludedText) {
assertTrue(errorMessage + " expected included:<" + expectedIncludedText + "> but was not included in:<" + text + ">",
text.contains(expectedIncludedText));
}
public void shouldNotInclude(String expectedNotIncludedText) {
assertFalse(errorMessage + " not expected included:<" + expectedNotIncludedText + "> but was included in:<" + text + ">",
text.contains(expectedNotIncludedText));
}
}
then we can get nicer syntax to express our intent for verification.
dropDownList.shouldDisplayLabel -> dropDownList.lable().shouldEqual(expectedLabel)
dropDownList.shouldDisplayIndex -> dropDownList.index().shouldEqual(expectedIndex)
and I can do something like verify css style includes a particular style:
dropDownList.css().shouldInclude(”errorField”)
We can add more methods to TextDSL class. or we can create other DSL class we want to verify the object we want.
Later on, I will post the source code so that you can see the whole implementation.
May 6th, 2008 at 5:53 am
HI,
Its very useful for many java developers who are new to DSL.
Regards,
Rajesh
August 17th, 2008 at 1:53 pm
Your blog is interesting!
Keep up the good work!