001 /* 002 * Created on Jun 4, 2007 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 005 * the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 010 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 011 * specific language governing permissions and limitations under the License. 012 * 013 * Copyright @2007-2009 the original author or authors. 014 */ 015 package org.fest.swing.junit.ant; 016 017 import static org.apache.tools.ant.taskdefs.optional.junit.XMLConstants.ERROR; 018 import junit.framework.Test; 019 020 import org.apache.tools.ant.taskdefs.optional.junit.JUnitTest; 021 import org.fest.swing.image.ImageException; 022 import org.fest.swing.junit.xml.XmlNode; 023 024 /** 025 * Understands a JUnit XML report formatter that takes a screenshot when a GUI test fails. 026 * <p> 027 * <strong>Note:</strong> A test is consider a GUI test if it is marked with the annotation 028 * <code>{@link org.fest.swing.annotation.GUITest}</code>. 029 * </p> 030 * 031 * @author Alex Ruiz 032 */ 033 public final class ScreenshotOnFailureResultFormatter extends XmlJUnitResultFormatter { 034 035 private ScreenshotXmlWriter screenshotXmlWriter; 036 037 /** 038 * Execution of the JUnit test suite started. Internally, this method creates the writer responsible for embedding 039 * a screenshot of the desktop in the XML report. 040 * @param suite the JUnit test suite. 041 */ 042 @Override protected void onStartTestSuite(JUnitTest suite) { 043 try { 044 screenshotXmlWriter = new ScreenshotXmlWriter(); 045 } catch (ImageException e) { 046 informCannotTakeScreenshots(e); 047 } 048 } 049 050 private void informCannotTakeScreenshots(ImageException error) { 051 XmlNode errorNode = xmlRootNode().addNewNode(ERROR); 052 writeErrorAndStackTrace(error, errorNode); 053 } 054 055 /** 056 * A test failed. This method embeds a screenshot of the desktop if the failing test is a GUI test. 057 * @param test the failing test. 058 * @param error the cause of the failure or error. 059 * @param target the element in the XML report containing information about the failure. 060 */ 061 @Override protected void onFailureOrError(Test test, Throwable error, XmlNode target) { 062 if (screenshotXmlWriter == null) return; 063 screenshotXmlWriter.writeScreenshot(target, test); 064 } 065 }