Assume you have some images on your page under test, which has some images. You should be sure they are really displayed. Simple validation on image control presence doesn’t solves the problem, because <img> could have invalid source (src attribute). We will enhance our basic test with method which could be used like:
assertImagePresent("imgUnderTestId")
assertImagePresent() method could be used with img component id or with XPath locator to assert that image has nonzero width and height (such technique used because width and height under assertion are real dimensions of target image in already rendered page).
We will enhance our basic SeleniumTest (used as superclass for all integration test cases) again:
public abstract class SeleniumTest extends SeleneseTestCase {
static String context = "http://localhost:8080/app/"
public void setUp() {
setUp context, "*firefox"
}
...
def assertImagePresent(String imageIdOrXPathLocator) {
assertTrue Integer.valueOf(getDomAttribute(imageIdOrXPathLocator, "naturalWidth")) > 0
assertTrue Integer.valueOf(getDomAttribute(imageIdOrXPathLocator, "naturalHeight")) > 0
}
def getDomAttribute(String elementIdOrXPathLocator, String attribute) {
if (elementIdOrXPathLocator.startsWith("//")) {
def expression = "window.document.evaluate('${StringEscapeUtils.escapeJavaScript(elementIdOrXPathLocator)}', window.document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue['$attribute'];"
return selenium.getEval(expression)
} else {
return selenium.getEval("window.document.getElementById('$elementIdOrXPathLocator')['$attribute'];")
}
}
...
}