How to use TestNGException class of org.testng package

Best Testng code snippet using org.testng.TestNGException

TestNGExceptionorg.testng.TestNGException

This is base class of all testng Exceptions i.e every exception of testng extends this.

Code Snippets

Here are code snippets that can help you understand more how developers are using

Source:ClassHelper.java Github

copy

Full Screen

...12import org.testng.IMethodSelector;13import org.testng.IObjectFactory;14import org.testng.IObjectFactory2;15import org.testng.ITestObjectFactory;16import org.testng.TestNGException;17import org.testng.TestRunner;18import org.testng.annotations.IAnnotation;19import org.testng.annotations.IFactoryAnnotation;20import org.testng.annotations.IParametersAnnotation;21import org.testng.collections.Sets;22import org.testng.internal.annotations.IAnnotationFinder;23import org.testng.junit.IJUnitTestRunner;24import org.testng.xml.XmlTest;25/**26 * Utility class for different class manipulations.27 */28public final class ClassHelper {29 private static final String JUNIT_TESTRUNNER= "org.testng.junit.JUnitTestRunner";30 private static final String JUNIT_4_TESTRUNNER = "org.testng.junit.JUnit4TestRunner";31 /** The additional class loaders to find classes in. */32 private static final List<ClassLoader> m_classLoaders = new Vector<>();33 /** Add a class loader to the searchable loaders. */34 public static void addClassLoader(final ClassLoader loader) {35 m_classLoaders.add(loader);36 }37 /** Hide constructor. */38 private ClassHelper() {39 // Hide Constructor40 }41 public static <T> T newInstance(Class<T> clazz) {42 try {43 T instance = clazz.newInstance();44 return instance;45 }46 catch(IllegalAccessException iae) {47 throw new TestNGException("Class " + clazz.getName()48 + " does not have a no-args constructor", iae);49 }50 catch(InstantiationException ie) {51 throw new TestNGException("Cannot instantiate class " + clazz.getName(), ie);52 }53 catch(ExceptionInInitializerError eiierr) {54 throw new TestNGException("An exception occurred in static initialization of class "55 + clazz.getName(), eiierr);56 }57 catch(SecurityException se) {58 throw new TestNGException(se);59 }60 }61 public static <T> T newInstance(Constructor<T> constructor, Object... parameters) {62 try {63 return constructor.newInstance(parameters);64 } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {65 throw new TestNGException("Cannot instantiate class " + constructor.getDeclaringClass().getName(), e);66 }67 }68 /**69 * Tries to load the specified class using the context ClassLoader or if none,70 * than from the default ClassLoader. This method differs from the standard71 * class loading methods in that it does not throw an exception if the class72 * is not found but returns null instead.73 *74 * @param className the class name to be loaded.75 *76 * @return the class or null if the class is not found.77 */78 public static Class<?> forName(final String className) {79 Vector<ClassLoader> allClassLoaders = new Vector<>();80 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();81 if (contextClassLoader != null) {82 allClassLoaders.add(contextClassLoader);83 }84 if (m_classLoaders != null) {85 allClassLoaders.addAll(m_classLoaders);86 }87 for (ClassLoader classLoader : allClassLoaders) {88 if (null == classLoader) {89 continue;90 }91 try {92 return classLoader.loadClass(className);93 }94 catch(ClassNotFoundException ex) {95 // With additional class loaders, it is legitimate to ignore ClassNotFoundException96 if (null == m_classLoaders || m_classLoaders.size() == 0) {97 logClassNotFoundError(className, ex);98 }99 }100 }101 try {102 return Class.forName(className);103 }104 catch(ClassNotFoundException cnfe) {105 logClassNotFoundError(className, cnfe);106 return null;107 }108 }109 private static void logClassNotFoundError(String className, Exception ex) {110 Utils.log("ClassHelper", 2, "Could not instantiate " + className111 + " : Class doesn't exist (" + ex.getMessage() + ")");112 }113 /**114 * For the given class, returns the method annotated with &#64;Factory or null115 * if none is found. This method does not search up the superclass hierarchy.116 * If more than one method is @Factory annotated, a TestNGException is thrown.117 * @param cls The class to search for the @Factory annotation.118 * @param finder The finder (JDK 1.4 or JDK 5.0+) use to search for the annotation.119 *120 * @return the @Factory <CODE>method</CODE> or null121 */122 public static ConstructorOrMethod findDeclaredFactoryMethod(Class<?> cls,123 IAnnotationFinder finder) {124 ConstructorOrMethod result = null;125 for (Method method : getAvailableMethods(cls)) {126 IFactoryAnnotation f = finder.findAnnotation(method, IFactoryAnnotation.class);127 if (null != f) {128 result = new ConstructorOrMethod(method);129 result.setEnabled(f.getEnabled());130 break;131 }132 }133 if (result == null) {134 for (Constructor constructor : cls.getDeclaredConstructors()) {135 IAnnotation f = finder.findAnnotation(constructor, IFactoryAnnotation.class);136 if (f != null) {137 result = new ConstructorOrMethod(constructor);138 }139 }140 }141 // If we didn't find anything, look for nested classes142// if (null == result) {143// Class[] subClasses = cls.getClasses();144// for (Class subClass : subClasses) {145// result = findFactoryMethod(subClass, finder);146// if (null != result) {147// break;148// }149// }150// }151 return result;152 }153 /**154 * Extract all callable methods of a class and all its super (keeping in mind155 * the Java access rules).156 */157 public static Set<Method> getAvailableMethods(Class<?> clazz) {158 Set<Method> methods = Sets.newHashSet();159 methods.addAll(Arrays.asList(clazz.getDeclaredMethods()));160 Class<?> parent = clazz.getSuperclass();161 while (null != parent) {162 methods.addAll(extractMethods(clazz, parent, methods));163 parent = parent.getSuperclass();164 }165 return methods;166 }167 public static IJUnitTestRunner createTestRunner(TestRunner runner) {168 try {169 //try to get runner for JUnit 4 first170 Class.forName("org.junit.Test");171 IJUnitTestRunner tr = (IJUnitTestRunner) ClassHelper.forName(JUNIT_4_TESTRUNNER).newInstance();172 tr.setTestResultNotifier(runner);173 return tr;174 } catch (Throwable t) {175 Utils.log("ClassHelper", 2, "JUnit 4 was not found on the classpath");176 try {177 //fallback to JUnit 3178 Class.forName("junit.framework.Test");179 IJUnitTestRunner tr = (IJUnitTestRunner) ClassHelper.forName(JUNIT_TESTRUNNER).newInstance();180 tr.setTestResultNotifier(runner);181 return tr;182 } catch (Exception ex) {183 Utils.log("ClassHelper", 2, "JUnit 3 was not found on the classpath");184 //there's no JUnit on the classpath185 throw new TestNGException("Cannot create JUnit runner", ex);186 }187 }188 }189 private static Set<Method> extractMethods(Class<?> childClass, Class<?> clazz,190 Set<Method> collected) {191 Set<Method> methods = Sets.newHashSet();192 Method[] declaredMethods = clazz.getDeclaredMethods();193 Package childPackage = childClass.getPackage();194 Package classPackage = clazz.getPackage();195 boolean isSamePackage = false;196 if ((null == childPackage) && (null == classPackage)) {197 isSamePackage = true;198 }199 if ((null != childPackage) && (null != classPackage)) {200 isSamePackage = childPackage.getName().equals(classPackage.getName());201 }202 for (Method method : declaredMethods) {203 int methodModifiers = method.getModifiers();204 if ((Modifier.isPublic(methodModifiers) || Modifier.isProtected(methodModifiers))205 || (isSamePackage && !Modifier.isPrivate(methodModifiers))) {206 if (!isOverridden(method, collected) && !Modifier.isAbstract(methodModifiers)) {207 methods.add(method);208 }209 }210 }211 return methods;212 }213 private static boolean isOverridden(Method method, Set<Method> collectedMethods) {214 Class<?> methodClass = method.getDeclaringClass();215 Class<?>[] methodParams = method.getParameterTypes();216 for (Method m: collectedMethods) {217 Class<?>[] paramTypes = m.getParameterTypes();218 if (method.getName().equals(m.getName())219 && methodClass.isAssignableFrom(m.getDeclaringClass())220 && methodParams.length == paramTypes.length) {221 boolean sameParameters = true;222 for (int i= 0; i < methodParams.length; i++) {223 if (!methodParams[i].equals(paramTypes[i])) {224 sameParameters = false;225 break;226 }227 }228 if (sameParameters) {229 return true;230 }231 }232 }233 return false;234 }235 public static IMethodSelector createSelector(org.testng.xml.XmlMethodSelector selector) {236 try {237 Class<?> cls = Class.forName(selector.getClassName());238 return (IMethodSelector) cls.newInstance();239 }240 catch(Exception ex) {241 throw new TestNGException("Couldn't find method selector : " + selector.getClassName(), ex);242 }243 }244 /**245 * Create an instance for the given class.246 */247 public static Object createInstance(Class<?> declaringClass,248 Map<Class, IClass> classes,249 XmlTest xmlTest,250 IAnnotationFinder finder,251 ITestObjectFactory objectFactory)252 {253 if (objectFactory instanceof IObjectFactory) {254 return createInstance1(declaringClass, classes, xmlTest, finder,255 (IObjectFactory) objectFactory);256 } else if (objectFactory instanceof IObjectFactory2) {257 return createInstance2(declaringClass, (IObjectFactory2) objectFactory);258 } else {259 throw new AssertionError("Unknown object factory type:" + objectFactory);260 }261 }262 private static Object createInstance2(Class<?> declaringClass, IObjectFactory2 objectFactory) {263 return objectFactory.newInstance(declaringClass);264 }265 public static Object createInstance1(Class<?> declaringClass,266 Map<Class, IClass> classes,267 XmlTest xmlTest,268 IAnnotationFinder finder,269 IObjectFactory objectFactory) {270 Object result = null;271 try {272 //273 // Any annotated constructor?274 //275 Constructor<?> constructor = findAnnotatedConstructor(finder, declaringClass);276 if (null != constructor) {277 IParametersAnnotation annotation = finder.findAnnotation(constructor, IParametersAnnotation.class);278 String[] parameterNames = annotation.getValue();279 Object[] parameters = Parameters.createInstantiationParameters(constructor,280 "@Parameters",281 finder,282 parameterNames,283 xmlTest.getAllParameters(),284 xmlTest.getSuite());285 result = objectFactory.newInstance(constructor, parameters);286 }287 //288 // No, just try to instantiate the parameterless constructor (or the one289 // with a String)290 //291 else {292 // If this class is a (non-static) nested class, the constructor contains a hidden293 // parameter of the type of the enclosing class294 Class<?>[] parameterTypes = new Class[0];295 Object[] parameters = new Object[0];296 Class<?> ec = getEnclosingClass(declaringClass);297 boolean isStatic = 0 != (declaringClass.getModifiers() & Modifier.STATIC);298 // Only add the extra parameter if the nested class is not static299 if ((null != ec) && !isStatic) {300 parameterTypes = new Class[] { ec };301 // Create an instance of the enclosing class so we can instantiate302 // the nested class (actually, we reuse the existing instance).303 IClass enclosingIClass = classes.get(ec);304 Object[] enclosingInstances;305 if (null != enclosingIClass) {306 enclosingInstances = enclosingIClass.getInstances(false);307 if ((null == enclosingInstances) || (enclosingInstances.length == 0)) {308 Object o = objectFactory.newInstance(ec.getConstructor(parameterTypes));309 enclosingIClass.addInstance(o);310 enclosingInstances = new Object[] { o };311 }312 }313 else {314 enclosingInstances = new Object[] { ec.newInstance() };315 }316 Object enclosingClassInstance = enclosingInstances[0];317 // Utils.createInstance(ec, classes, xmlTest, finder);318 parameters = new Object[] { enclosingClassInstance };319 } // isStatic320 Constructor<?> ct;321 try {322 ct = declaringClass.getDeclaredConstructor(parameterTypes);323 }324 catch (NoSuchMethodException ex) {325 ct = declaringClass.getDeclaredConstructor(String.class);326 parameters = new Object[] { "Default test name" };327 // If ct == null here, we'll pass a null328 // constructor to the factory and hope it can deal with it329 }330 result = objectFactory.newInstance(ct, parameters);331 }332 }333 catch (TestNGException ex) {334 throw ex;335// throw new TestNGException("Couldn't instantiate class:" + declaringClass);336 }337 catch (NoSuchMethodException ex) {338 }339 catch (Throwable cause) {340 // Something else went wrong when running the constructor341 throw new TestNGException("An error occurred while instantiating class "342 + declaringClass.getName() + ": " + cause.getMessage(), cause);343 }344 if (result == null) {345 if (! Modifier.isPublic(declaringClass.getModifiers())) {346 //result should not be null347 throw new TestNGException("An error occurred while instantiating class "348 + declaringClass.getName() + ". Check to make sure it can be accessed/instantiated.");349// } else {350// Utils.log(ClassHelper.class.getName(), 2, "Couldn't instantiate class " + declaringClass);351 }352 }353 return result;354 }355 /**356 * Class.getEnclosingClass() only exists on JDK5, so reimplementing it357 * here.358 */359 private static Class<?> getEnclosingClass(Class<?> declaringClass) {360 Class<?> result = null;361 String className = declaringClass.getName();362 int index = className.indexOf("$");363 if (index != -1) {364 String ecn = className.substring(0, index);365 try {366 result = Class.forName(ecn);367 }368 catch (ClassNotFoundException e) {369 e.printStackTrace();370 }371 }372 return result;373 }374 /**375 * Find the best constructor given the parameters found on the annotation376 */377 private static Constructor<?> findAnnotatedConstructor(IAnnotationFinder finder,378 Class<?> declaringClass) {379 Constructor<?>[] constructors = declaringClass.getDeclaredConstructors();380 for (Constructor<?> result : constructors) {381 IParametersAnnotation annotation = finder.findAnnotation(result, IParametersAnnotation.class);382 if (null != annotation) {383 String[] parameters = annotation.getValue();384 Class<?>[] parameterTypes = result.getParameterTypes();385 if (parameters.length != parameterTypes.length) {386 throw new TestNGException("Parameter count mismatch: " + result + "\naccepts "387 + parameterTypes.length388 + " parameters but the @Test annotation declares "389 + parameters.length);390 }391 else {392 return result;393 }394 }395 }396 return null;397 }398 public static <T> T tryOtherConstructor(Class<T> declaringClass) {399 T result;400 try {401 // Special case for inner classes402 if (declaringClass.getModifiers() == 0) {403 return null;404 }405 Constructor<T> ctor = declaringClass.getConstructor(String.class);406 result = ctor.newInstance("Default test name");407 }408 catch (Exception e) {409 String message = e.getMessage();410 if ((message == null) && (e.getCause() != null)) {411 message = e.getCause().getMessage();412 }413 String error = "Could not create an instance of class " + declaringClass414 + ((message != null) ? (": " + message) : "")415 + ".\nPlease make sure it has a constructor that accepts either a String or no parameter.";416 throw new TestNGException(error);417 }418 return result;419 }420 /**421 * When given a file name to form a class name, the file name is parsed and divided422 * into segments. For example, "c:/java/classes/com/foo/A.class" would be divided423 * into 6 segments {"C:" "java", "classes", "com", "foo", "A"}. The first segment424 * actually making up the class name is [3]. This value is saved in m_lastGoodRootIndex425 * so that when we parse the next file name, we will try 3 right away. If 3 fails we426 * will take the long approach. This is just a optimization cache value.427 */428 private static int m_lastGoodRootIndex = -1;429 /**430 * Returns the Class object corresponding to the given name. The name may be431 * of the following form:432 * <ul>433 * <li>A class name: "org.testng.TestNG"</li>434 * <li>A class file name: "/testng/src/org/testng/TestNG.class"</li>435 * <li>A class source name: "d:\testng\src\org\testng\TestNG.java"</li>436 * </ul>437 *438 * @param file439 * the class name.440 * @return the class corresponding to the name specified.441 */442 public static Class<?> fileToClass(String file) {443 Class<?> result = null;444 if(!file.endsWith(".class") && !file.endsWith(".java")) {445 // Doesn't end in .java or .class, assume it's a class name446 if (file.startsWith("class ")) {447 file = file.substring("class ".length());448 }449 result = ClassHelper.forName(file);450 if (null == result) {451 throw new TestNGException("Cannot load class from file: " + file);452 }453 return result;454 }455 int classIndex = file.lastIndexOf(".class");456 if (-1 == classIndex) {457 classIndex = file.lastIndexOf(".java");458//459// if(-1 == classIndex) {460// result = ClassHelper.forName(file);461//462// if (null == result) {463// throw new TestNGException("Cannot load class from file: " + file);464// }465//466// return result;467// }468//469 }470 // Transforms the file name into a class name.471 // Remove the ".class" or ".java" extension.472 String shortFileName = file.substring(0, classIndex);473 // Split file name into segments. For example "c:/java/classes/com/foo/A"474 // becomes {"c:", "java", "classes", "com", "foo", "A"}475 String[] segments = shortFileName.split("[/\\\\]", -1);476 //477 // Check if the last good root index works for this one. For example, if the previous478 // name was "c:/java/classes/com/foo/A.class" then m_lastGoodRootIndex is 3 and we479 // try to make a class name ignoring the first m_lastGoodRootIndex segments (3). This480 // will succeed rapidly if the path is the same as the one from the previous name.481 //482 if (-1 != m_lastGoodRootIndex) {483 StringBuilder className = new StringBuilder(segments[m_lastGoodRootIndex]);484 for (int i = m_lastGoodRootIndex + 1; i < segments.length; i++) {485 className.append(".").append(segments[i]);486 }487 result = ClassHelper.forName(className.toString());488 if (null != result) {489 return result;490 }491 }492 //493 // We haven't found a good root yet, start by resolving the class from the end segment494 // and work our way up. For example, if we start with "c:/java/classes/com/foo/A"495 // we'll start by resolving "A", then "foo.A", then "com.foo.A" until something496 // resolves. When it does, we remember the path we are at as "lastGoodRoodIndex".497 //498 // TODO CQ use a StringBuffer here499 String className = null;500 for (int i = segments.length - 1; i >= 0; i--) {501 if (null == className) {502 className = segments[i];503 }504 else {505 className = segments[i] + "." + className;506 }507 result = ClassHelper.forName(className);508 if (null != result) {509 m_lastGoodRootIndex = i;510 break;511 }512 }513 if (null == result) {514 throw new TestNGException("Cannot load class from file: " + file);515 }516 return result;517 }518}...

Full Screen

Full Screen

Source:FactoryMethod.java Github

copy

Full Screen

...12import org.testng.ITestContext;13import org.testng.ITestMethodFinder;14import org.testng.ITestNGMethod;15import org.testng.ITestObjectFactory;16import org.testng.TestNGException;17import org.testng.annotations.IFactoryAnnotation;18import org.testng.collections.Lists;19import org.testng.collections.Maps;20import org.testng.internal.annotations.IAnnotationFinder;21import org.testng.xml.XmlTest;22/**23 * This class represents a method annotated with @Factory24 */25public class FactoryMethod extends BaseTestMethod {26 private static final long serialVersionUID = -7329918821346197099L;27 private final IFactoryAnnotation factoryAnnotation;28 private final Object m_instance;29 private final XmlTest m_xmlTest;30 private final ITestContext m_testContext;31 private final ITestObjectFactory objectFactory;32 public FactoryMethod(ConstructorOrMethod com, Object instance, XmlTest xmlTest, IAnnotationFinder annotationFinder,33 ITestContext testContext, ITestObjectFactory objectFactory) {34 super(com.getName(), com, annotationFinder, instance);35 Utils.checkInstanceOrStatic(instance, com.getMethod());36 Utils.checkReturnType(com.getMethod(), Object[].class, IInstanceInfo[].class);37 Class<?> declaringClass = com.getDeclaringClass();38 if (instance != null && ! declaringClass.isAssignableFrom(instance.getClass())) {39 throw new TestNGException("Mismatch between instance/method classes:"40 + instance.getClass() + " " + declaringClass);41 }42 if (instance == null && com.getMethod() != null && !Modifier.isStatic(com.getMethod().getModifiers())) {43 throw new TestNGException("An inner factory method MUST be static. But '" + com.getMethod().getName() + "' from '" + declaringClass.getName() + "' is not.");44 }45 if (com.getMethod() != null && !Modifier.isPublic(com.getMethod().getModifiers())) {46 try {47 com.getMethod().setAccessible(true);48 } catch (SecurityException e) {49 throw new TestNGException(com.getMethod().getName() + " must be public", e);50 }51 }52 factoryAnnotation = annotationFinder.findAnnotation(com, IFactoryAnnotation.class);53 m_instance = instance;54 m_xmlTest = xmlTest;55 m_testContext = testContext;56 NoOpTestClass tc = new NoOpTestClass();57 tc.setTestClass(declaringClass);58 m_testClass = tc;59 this.objectFactory = objectFactory;60 m_groups = getAllGroups(declaringClass, xmlTest, annotationFinder);61 }62 private static String[] getAllGroups(Class<?> declaringClass, XmlTest xmlTest,63 IAnnotationFinder annotationFinder) {64 // Find the groups of the factory => all groups of all test methods65 ITestMethodFinder testMethodFinder = new TestNGMethodFinder(new RunInfo(), annotationFinder);66 ITestNGMethod[] testMethods = testMethodFinder.getTestMethods(declaringClass, xmlTest);67 Set<String> groups = new HashSet<>();68 for (ITestNGMethod method : testMethods) {69 groups.addAll(Arrays.asList(method.getGroups()));70 }71 return groups.toArray(new String[groups.size()]);72 }73 public Object[] invoke() {74 List<Object> result = Lists.newArrayList();75 Map<String, String> allParameterNames = Maps.newHashMap();76 Iterator<Object[]> parameterIterator =77 Parameters.handleParameters(this,78 allParameterNames,79 m_instance,80 new Parameters.MethodParameters(m_xmlTest.getAllParameters(),81 findMethodParameters(m_xmlTest),82 null, null, m_testContext,83 null /* testResult */),84 m_xmlTest.getSuite(),85 m_annotationFinder,86 null /* fedInstance */).parameters;87 try {88 List<Integer> indices = factoryAnnotation.getIndices();89 int position = 0;90 while (parameterIterator.hasNext()) {91 Object[] parameters = parameterIterator.next();92 ConstructorOrMethod com = getConstructorOrMethod();93 if (com.getMethod() != null) {94 Object[] testInstances = (Object[]) com.getMethod().invoke(m_instance, parameters);95 if (indices == null || indices.isEmpty()) {96 for (Object testInstance : testInstances) {97 result.add(testInstance);98 }99 } else {100 for (Integer index : indices) {101 int i = index - position;102 if (i >= 0 && i < testInstances.length) {103 result.add(testInstances[i]);104 }105 }106 }107 position += testInstances.length;108 } else {109 if (indices == null || indices.isEmpty() || indices.contains(position)) {110 Object instance;111 if (objectFactory instanceof IObjectFactory) {112 instance = ((IObjectFactory) objectFactory).newInstance(com.getConstructor(), parameters);113 } else if (objectFactory instanceof IObjectFactory2) {114 instance = ((IObjectFactory2) objectFactory).newInstance(com.getDeclaringClass());115 } else {116 throw new IllegalStateException("Unsupported ITestObjectFactory " + objectFactory.getClass());117 }118 result.add(instance);119 }120 position++;121 }122 }123 } catch (Throwable t) {124 ConstructorOrMethod com = getConstructorOrMethod();125 throw new TestNGException("The factory method "126 + com.getDeclaringClass() + "." + com.getName()127 + "() threw an exception", t);128 }129 return result.toArray(new Object[result.size()]);130 }131 @Override132 public ITestNGMethod clone() {133 throw new IllegalStateException("clone is not supported for FactoryMethod");134 }135}...

Full Screen

Full Screen

Source:BMNGListener.java Github

copy

Full Screen

...27import org.testng.ITestContext;28import org.testng.ITestListener;29import org.testng.ITestNGListener;30import org.testng.ITestResult;31import org.testng.TestNGException;32import org.testng.annotations.Listeners;33import java.lang.reflect.Method;34/**35 * Class which provides the ability to load Byteman rules into TestNG style tests.36 * A class which inherits from this class will inherit the ability to have BMScript and BMRule37 * annotations processed during testing.38 */39public class BMNGListener extends BMNGAbstractRunner implements IInvokedMethodListener, ITestListener40{41 // TODO work out what to do if tests are run in parallel and their rule sets overlap or have ocnflicting behaviour42 private boolean checkBMNGListener(Class<?> clazz)43 {44 Listeners listeners = clazz.getAnnotation(Listeners.class);45 if (listeners == null) {46 return false;47 }48 Class<? extends ITestNGListener>[] clazzarray = listeners.value();49 for (int i = 0; i < clazzarray.length; i++) {50 if (clazzarray[i] == BMNGListener.class) {51 return true;52 }53 }54 return false;55 }56 public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {57 Method javaMethod = method.getTestMethod().getMethod();58 Class clazz = javaMethod.getDeclaringClass();59 if (!checkBMNGListener(clazz)) {60 return;61 }62 if (clazz != currentClazz) {63 switchClass(clazz);64 }65 try {66 bmngBeforeTest(javaMethod);67 } catch (Exception e) {68 try {69 BMUnitConfigState.resetConfigurationState(javaMethod);70 } catch(Exception e1) {71 }72 throw new TestNGException(e);73 }74 }75 public void afterInvocation(IInvokedMethod method, ITestResult testResult) {76 Method javaMethod = method.getTestMethod().getMethod();77 Class clazz = javaMethod.getDeclaringClass();78 if (!checkBMNGListener(clazz)) {79 return;80 }81 try {82 bmngAfterTest(javaMethod);83 try {84 BMUnitConfigState.resetConfigurationState(javaMethod);85 } catch(Exception e1) {86 }87 } catch (Exception e) {88 throw new TestNGException(e);89 }90 }91 public void onTestStart(ITestResult result) {92 }93 public void onTestSuccess(ITestResult result) {94 }95 public void onTestFailure(ITestResult result) {96 }97 public void onTestSkipped(ITestResult result) {98 }99 public void onTestFailedButWithinSuccessPercentage(ITestResult result) {100 }101 public void onStart(ITestContext context) {102 /*103 * TestNG calls onStart for all classes in a suite before running any104 * of their test methods which is basically a complete pile of pooh.105 *106 * so we don't do class specific before processing at this level.107 * instead we do it lazily when methods are notified by detecting108 * changes in the current class at that point109 Class<?> testClass = context.getCurrentXmlTest().getXmlClasses().get(0).getSupportClass();110 try {111 bmngBeforeClass(testClass);112 } catch (Exception e) {113 try {114 BMUnitConfigState.resetConfigurationState(testClass);115 } catch(Exception e1) {116 }117 throw new TestNGException(e);118 }119 */120 }121 public void onFinish(ITestContext context) {122 /*123 * TestNG calls onFinish for all classes in a suite after running all124 * of their test methods which is basically a complete pile of pooh.125 *126 * so we don't do after class specific processing at this level.127 * instead we do it pre-emptively when methods are notified by128 * detecting changes in the current class at that point129 Class<?> testClass = context.getCurrentXmlTest().getXmlClasses().get(0).getSupportClass();130 try {131 bmngAfterClass(testClass);132 } catch (Exception e) {133 try {134 BMUnitConfigState.resetConfigurationState(testClass);135 } catch(Exception e1) {136 }137 throw new TestNGException(e);138 }139 */140 // run any left over after class processing141 switchClass(null);142 }143}...

Full Screen

Full Screen

Source:TestRunner.java Github

copy

Full Screen

...4import lombok.extern.slf4j.Slf4j;5import org.testng.ITestResult;6import org.testng.TestListenerAdapter;7import org.testng.TestNG;8import org.testng.TestNGException;9import java.io.IOException;10import java.util.ArrayList;11import java.util.List;12/**13 * The entry point to the automation. The {@link TestRunner} handles bootstrapping TestNG and populating the14 * populating the {@link CommandLineParams}.15 *16 * @author <a href="mailto:JGraham@aimconsulting.com">Justin Graham</a>17 * @since 2/15/1618 */19@Slf4j20public class TestRunner {21 private static final String TEST_PACKAGE = "icici.test";22 private static final String TEST_CLASS_ENDING = "Test";23 public static void main(String[] args) throws Exception {24 // Get the default state25 CommandLineParams params = CommandLineParams.get();26 // Override the default state with user supplied values27 new JCommander(params, args);28 // Bootstrap TestNG to allow building an executable JAR29 final TestNG testNG = new TestNG();30 final TestListenerAdapter adapter = new TestReporter();31 testNG.setTestClasses(getTests());32 testNG.addListener(adapter);33 testNG.run();34 // If testNG contains failures the Jar needs to throw an exception for Jenkins to fail the build35 if (testNG.hasFailure()) reportFailures(adapter);36 }37 /**38 * This function uses reflection to find the TestNG test classes stored within the {@link TestRunner#TEST_PACKAGE}39 * with the name ending with {@link TestRunner#TEST_CLASS_ENDING}.40 *41 * @return an array of TestNG test classes42 * @throws IOException if the attempt to read class path resources (jar files or directories) failed.43 * @throws ClassNotFoundException if the class to load was not found44 */45 private static Class[] getTests() throws IOException, ClassNotFoundException {46 final ClassLoader classLoader = TestRunner.class.getClassLoader();47 final ClassPath classPath = ClassPath.from(classLoader);48 final List<Class> testClasses = new ArrayList<>();49 for (ClassPath.ClassInfo info : classPath.getTopLevelClassesRecursive(TEST_PACKAGE)) {50 if (info.getName().endsWith(TEST_CLASS_ENDING)) {51 testClasses.add(classLoader.loadClass(info.getName()));52 }53 }54 return testClasses.toArray(new Class[testClasses.size()]);55 }56 /**57 * Builds a detailed {@link TestNGException} containing all failures58 *59 * @param tla the {@link TestListenerAdapter} returned after a TestNG run60 * @throws TestNGException once detailed message has been built61 */62 private static void reportFailures(TestListenerAdapter tla) throws TestNGException {63 final StringBuilder builder = new StringBuilder();64 final List<ITestResult> testFailures = tla.getFailedTests();65 if (testFailures.size() > 0) {66 builder.append("Failed Tests:\n");67 builder.append(buildErrorMessage(testFailures));68 }69 final List<ITestResult> configFailures = tla.getConfigurationFailures();70 if (configFailures.size() > 0) {71 builder.append("Configuration Failures:\n");72 builder.append(buildErrorMessage(configFailures));73 }74 throw new TestNGException(builder.toString());75 }76 /**77 * Creates a detailed message of the test failures78 *79 * @param failures the test failures from a TestNG run80 * @return the detailed test failure message81 */82 private static String buildErrorMessage(List<ITestResult> failures) {83 final StringBuilder builder = new StringBuilder();84 for (ITestResult tr : failures) {85 builder.append("\t")86 .append(tr.getMethod().getMethodName())87 .append(": ")88 .append(tr.getThrowable().getMessage())...

Full Screen

Full Screen

Source:FactoryIntegrationTest.java Github

copy

Full Screen

1package test.factory;2import org.testng.Assert;3import org.testng.TestListenerAdapter;4import org.testng.TestNG;5import org.testng.TestNGException;6import org.testng.annotations.Test;7import test.SimpleBaseTest;8import static org.assertj.core.api.Assertions.assertThat;9import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;10public class FactoryIntegrationTest extends SimpleBaseTest {11 @Test(description = "https://github.com/cbeust/testng/issues/876")12 public void testExceptionWithNonStaticFactoryMethod() {13 TestNG tng = create(GitHub876Sample.class);14 try {15 tng.run();16 failBecauseExceptionWasNotThrown(TestNGException.class);17 } catch (TestNGException e) {18 assertThat(e).hasMessage("\nCan't invoke public java.lang.Object[] test.factory.GitHub876Sample.createInstances(): either make it static or add a no-args constructor to your class");19 }20 }21 @Test22 public void testNonPublicFactoryMethodShouldWork() {23 TestNG tng = create(NonPublicFactoryMethodSample.class);24 TestListenerAdapter tla = new TestListenerAdapter();25 tng.addListener(tla);26 tng.run();27 Assert.assertEquals(tla.getPassedTests().size(), 2);28 }29 @Test30 public void testExceptionWithBadFactoryMethodReturnType() {31 TestNG tng = create(BadFactoryMethodReturnTypeSample.class);32 try {33 tng.run();34 failBecauseExceptionWasNotThrown(TestNGException.class);35 } catch (TestNGException e) {36 assertThat(e).hasMessage("\ntest.factory.BadFactoryMethodReturnTypeSample.createInstances MUST return [ java.lang.Object[] or org.testng.IInstanceInfo[] ] but returns java.lang.Object");37 }38 }39}...

Full Screen

Full Screen

Source:A018253682Case.java Github

copy

Full Screen

1package com.domain.test;2import com.domain.api.utils.ExcelUtil;3import com.domain.api.utils.Log;4import com.domain.entity.A018253682;5import org.testng.TestNGException;6import org.testng.annotations.DataProvider;7import org.testng.annotations.Test;8/**9 * Created by pei hao on 2021/9/1.10 */11public class A018253682Case {12 @DataProvider(name = "ExcelData")13 public Object[][] getData(){14 Object[][] result = null;15 try {16 result = ExcelUtil.getExcelData(new A018253682(), "登录案例");17 }catch (TestNGException e){18 Log.error("获取数据失败");19 }20 return result;21 }22 @Test(dataProvider ="ExcelData")23 public void testLogin001(String id, String caseName, String loginName, String loginPwd,24 String keyword1, String keyword2, String keyword3)throws Exception{25 A018253682 a01825368= new A018253682();26 a01825368.cookie="11111";27 a01825368.disname =loginName;28 a01825368.age =caseName;29 a01825368.run();30// Assert.assertEquals(a01825368.name,"qqqq");31 }...

Full Screen

Full Screen

Source:DepondMethod_PreviousClass.java Github

copy

Full Screen

1package testNG;2import org.testng.TestNGException;3import org.testng.annotations.AfterMethod;4import org.testng.annotations.AfterSuite;5import org.testng.annotations.AfterTest;6import org.testng.annotations.BeforeSuite;7import org.testng.annotations.Test;8public class DepondMethod_PreviousClass {9 @Test10 public void launchBroswer() {11 System.out.println("Launch Broswer -1");12 }13 @Test(dependsOnMethods = "launchBroswer")14 public void loginApplication() throws TestNGException {15 System.out.println("Login Application -2");16 }17 @Test(dependsOnMethods = "loginApplication")18 public void navigateToMenu() {19 System.out.println("Navigate To Account StatateMent -3");20 }21 @Test(dependsOnMethods = "navigateToMenu")22 public void viewAccStatement() {23 System.out.println("View Account Statement - 4");24 }25 @Test//(dependsOnMethods = "viewAccStatement")26 public void logoutApplication() {27 System.out.println("Logout the Application - 5");28 }...

Full Screen

Full Screen

Source:YamlParser.java Github

copy

Full Screen

1package org.testng.internal;2import org.testng.TestNGException;3import org.testng.xml.ISuiteParser;4import org.testng.xml.Parser;5import org.testng.xml.XmlSuite;6import java.io.FileNotFoundException;7import java.io.InputStream;8public class YamlParser implements ISuiteParser {9 @Override10 public XmlSuite parse(String filePath, InputStream is, boolean loadClasses)11 throws TestNGException {12 try {13 return Yaml.parse(filePath, is);14 } catch (FileNotFoundException e) {15 throw new TestNGException(e);16 }17 }18 @Override19 public boolean accept(String fileName) {20 return Parser.hasFileScheme(fileName) && fileName.endsWith(".yaml");21 }22}...

Full Screen

Full Screen

TestNGException

Using AI Code Generation

copy

Full Screen

1package org.testng;2public class TestNGException extends RuntimeException {3 private static final long serialVersionUID = 1L;4 public TestNGException(String message) {5 super(message);6 }7 public TestNGException(String message, Throwable cause) {8 super(message, cause);9 }10 public TestNGException(Throwable cause) {11 super(cause);12 }13}14package org.testng;15public class TestNGException extends RuntimeException {16 private static final long serialVersionUID = 1L;17 public TestNGException(String message) {18 super(message);19 }20 public TestNGException(String message, Throwable cause) {21 super(message, cause);22 }23 public TestNGException(Throwable cause) {24 super(cause);25 }26}27package org.testng;28public class TestNGException extends RuntimeException {29 private static final long serialVersionUID = 1L;30 public TestNGException(String message) {31 super(message);32 }33 public TestNGException(String message, Throwable cause) {34 super(message, cause);35 }36 public TestNGException(Throwable cause) {37 super(cause);38 }39}40package org.testng;41public class TestNGException extends RuntimeException {42 private static final long serialVersionUID = 1L;43 public TestNGException(String message) {44 super(message);45 }46 public TestNGException(String message, Throwable cause) {47 super(message, cause);48 }49 public TestNGException(Throwable cause) {50 super(cause);51 }52}53package org.testng;54public class TestNGException extends RuntimeException {55 private static final long serialVersionUID = 1L;56 public TestNGException(String message) {57 super(message);58 }59 public TestNGException(String message, Throwable cause) {60 super(message, cause);61 }62 public TestNGException(Throwable cause) {63 super(cause);64 }65}66package org.testng;67public class TestNGException extends RuntimeException {68 private static final long serialVersionUID = 1L;69 public TestNGException(String message) {70 super(message);71 }72 public TestNGException(String message, Throwable cause) {73 super(message, cause);74 }

Full Screen

Full Screen

TestNGException

Using AI Code Generation

copy

Full Screen

1import org.testng.TestNGException;2public class TestNGExceptionExample {3 public static void main(String[] args) {4 try {5 throw new TestNGException("TestNG exception");6 } catch (TestNGException e) {7 e.printStackTrace();8 }9 }10}11 at com.javacodegeeks.testng.TestNGExceptionExample.main(TestNGExceptionExample.java:10)

Full Screen

Full Screen

TestNGException

Using AI Code Generation

copy

Full Screen

1import org.testng.TestNGException;2public class TestNGExceptionDemo {3 public static void main(String args[]) {4 try {5 throw new TestNGException("TestNGException");6 } catch (TestNGException e) {7 System.out.println(e);8 }9 }10}11 at TestNGExceptionDemo.main(TestNGExceptionDemo.java:8)12 at TestNGExceptionDemo.main(TestNGExceptionDemo.java:8)13 at TestNGExceptionDemo.main(TestNGExceptionDemo.java:8)

Full Screen

Full Screen

TestNGException

Using AI Code Generation

copy

Full Screen

1import org.testng.TestNGException;2import org.testng.annotations.Test;3public class TestNGExceptionExample {4 public void test() {5 throw new TestNGException("This is TestNGException Example");6 }7}8at org.testng.TestNGExceptionExample.test(TestNGExceptionExample.java:9)9at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)10at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)11at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)12at java.lang.reflect.Method.invoke(Method.java:498)13at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:132)14at org.testng.internal.MethodInvocationHelper$1.runTestMethod(MethodInvocationHelper.java:273)15at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)16at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)17at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)18at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)19at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)20at org.testng.TestRunner.privateRun(TestRunner.java:648)21at org.testng.TestRunner.run(TestRunner.java:505)22at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)23at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)24at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)25at org.testng.SuiteRunner.run(SuiteRunner.java:364)26at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)27at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)28at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)29at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)30at org.testng.TestNG.run(TestNG.java:1049)31at org.testng.TestNG.privateMain(TestNG.java:1354)32at org.testng.TestNG.main(TestNG.java:1323)

Full Screen

Full Screen

TestNGException

Using AI Code Generation

copy

Full Screen

1import org.testng.TestNGException;2import org.testng.annotations.Test;3public class TestNGExceptionExample {4 public void testException() throws Exception {5 throw new TestNGException("TestNG Exception");6 }7}8 at org.testng.TestNGExceptionExample.testException(TestNGExceptionExample.java:10)9 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)10 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)11 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)12 at java.lang.reflect.Method.invoke(Method.java:498)13 at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:132)14 at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)15 at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)16 at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)17 at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)18 at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)19 at org.testng.TestRunner.privateRun(TestRunner.java:773)20 at org.testng.TestRunner.run(TestRunner.java:623)21 at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)22 at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)23 at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)24 at org.testng.SuiteRunner.run(SuiteRunner.java:259)25 at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)26 at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)27 at org.testng.TestNG.runSuitesSequentially(TestNG.java:1185)28 at org.testng.TestNG.runSuitesLocally(TestNG.java:1110)29 at org.testng.TestNG.runSuites(TestNG.java:1029)30 at org.testng.TestNG.run(TestNG.java:996)31 at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:116)32 at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)33 at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)34import org.testng.TestNGException;35import org.testng.annotations.Test;36public class TestNGExceptionExample {

Full Screen

Full Screen
copy
1public class PassByCopy{2 public static void changeName(Dog d){3 d.name = "Fido";4 }5 public static void main(String[] args){6 Dog d = new Dog("Maxx");7 System.out.println("name= "+ d.name);8 changeName(d);9 System.out.println("name= "+ d.name);10 }11}12class Dog{13 public String name;14 public Dog(String s){15 this.name = s;16 }17}18
Full Screen
copy
1Account account1 = new Account();2
Full Screen
copy
1public void test() {2 MyClass obj = null;3 init(obj);4 //After calling init method, obj still points to null5 //this is because obj is passed as value and not as reference.6}7private void init(MyClass objVar) {8 objVar = new MyClass();9}10
Full Screen

TestNG tutorial

TestNG is a Java-based open-source framework for test automation that includes various test types, such as unit testing, functional testing, E2E testing, etc. TestNG is in many ways similar to JUnit and NUnit. But in contrast to its competitors, its extensive features make it a lot more reliable framework. One of the major reasons for its popularity is its ability to structure tests and improve the scripts' readability and maintainability. Another reason can be the important characteristics like the convenience of using multiple annotations, reliance, and priority that make this framework popular among developers and testers for test design. You can refer to the TestNG tutorial to learn why you should choose the TestNG framework.

Chapters

  1. JUnit 5 vs. TestNG: Compare and explore the core differences between JUnit 5 and TestNG from the Selenium WebDriver viewpoint.
  2. Installing TestNG in Eclipse: Start installing the TestNG Plugin and learn how to set up TestNG in Eclipse to begin constructing a framework for your test project.
  3. Create TestNG Project in Eclipse: Get started with creating a TestNG project and write your first TestNG test script.
  4. Automation using TestNG: Dive into how to install TestNG in this Selenium TestNG tutorial, the fundamentals of developing an automation script for Selenium automation testing.
  5. Parallel Test Execution in TestNG: Here are some essential elements of parallel testing with TestNG in this Selenium TestNG tutorial.
  6. Creating TestNG XML File: Here is a step-by-step tutorial on creating a TestNG XML file to learn why and how it is created and discover how to run the TestNG XML file being executed in parallel.
  7. Automation with Selenium, Cucumber & TestNG: Explore for an in-depth tutorial on automation using Selenium, Cucumber, and TestNG, as TestNG offers simpler settings and more features.
  8. JUnit Selenium Tests using TestNG: Start running your regular and parallel tests by looking at how to run test cases in Selenium using JUnit and TestNG without having to rewrite the tests.
  9. Group Test Cases in TestNG: Along with the explanation and demonstration using relevant TestNG group examples, learn how to group test cases in TestNG.
  10. Prioritizing Tests in TestNG: Get started with how to prioritize test cases in TestNG for Selenium automation testing.
  11. Assertions in TestNG: Examine what TestNG assertions are, the various types of TestNG assertions, and situations that relate to Selenium automated testing.
  12. DataProviders in TestNG: Deep dive into learning more about TestNG's DataProvider and how to effectively use it in our test scripts for Selenium test automation.
  13. Parameterization in TestNG: Here are the several parameterization strategies used in TestNG tests and how to apply them in Selenium automation scripts.
  14. TestNG Listeners in Selenium WebDriver: Understand the various TestNG listeners to utilize them effectively for your next plan when working with TestNG and Selenium automation.
  15. TestNG Annotations: Learn more about the execution order and annotation attributes, and refer to the prerequisites required to set up TestNG.
  16. TestNG Reporter Log in Selenium: Find out how to use the TestNG Reporter Log and learn how to eliminate the need for external software with TestNG Reporter Class to boost productivity.
  17. TestNG Reports in Jenkins: Discover how to generate TestNG reports in Jenkins if you want to know how to create, install, and share TestNG reports in Jenkins.

Certification

You can push your abilities to do automated testing using TestNG and advance your career by earning a TestNG certification. Check out our TestNG certification.

YouTube

Watch this complete tutorial to learn how you can leverage the capabilities of the TestNG framework for Selenium automation testing.

Run Testng automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful