How can I ignore specifically annotated classes under TestNG? - java

Goal: Ignore test classes on runtime which have custom annotation set.
What I tried:
public void onStart(ITestContext context) {
if (context instanceof TestRunner) {
Map<Class<?>, ITestClass> notSkippedCl = new HashMap<Class<?>, ITestClass>();
TestRunner tRunner = (TestRunner) context;
Collection<ITestClass> testClasses = tRunner.getTestClasses();
for (Iterator<ITestClass> iterator = testClasses.iterator(); iterator.hasNext();) {
ITestClass rr = iterator.next();
Class<?> realClass = rr.getRealClass();
if (chechAnnotation(realClass))
{
notSkippedCl.put(realClass,rr);
}
}
try {
Field field = TestRunner.class.getDeclaredField("m_classMap");
field.setAccessible(true);
Map<Class<?>, ITestClass> mapClass = (Map<Class<?>, ITestClass>) field.get(tRunner);
mapClass.clear();
mapClass.putAll(notSkippedCl);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
onStart method is called before all test classes in package, So I get TestRunner here, which contains map of all test classes. I iterate throw each one, checking it Annotation and if I find one I add to new map. Then I override map of TestRunner. I was thinking that this will help me ignore classes without annotation, but I was wrong.
Maybe someone knows right solution, to Ignore test classes depending on custom annotation?
(parameter of the method cannot be changed)
P.S. setting #Test(enabled=false) annotation is not a solution in my situation
--EDIT_FAUND_SOLUTION--
I managed to create solution, not sure if there was easier way, but this works:
#Override
public void onStart(ITestContext context) {
if (context instanceof TestRunner) {
Set<ITestNGMethod> methodstodo = new HashSet<ITestNGMethod>();
TestRunner tRunner = (TestRunner) context;
ITestNGMethod[] allTestMethods = tRunner.getAllTestMethods();
SupportedBrowser currentBrowser = HelperMethod.getCurrentBrowser();
for(ITestNGMethod testMethod : allTestMethods)
{
Class<?> realClass = testMethod.getTestClass().getRealClass();
Set<SupportedBrowser> classBrowsers = getBrowsers(realClass);
if (classBrowsers.contains(currentBrowser)) {
methodstodo.add(testMethod);
}
}
try {
Field field = TestRunner.class.getDeclaredField("m_allTestMethods");
field.setAccessible(true);
field.set(tRunner, methodstodo.toArray(new ITestNGMethod[methodstodo.size()]));
} catch (Exception e) {
e.printStackTrace();
}
}
}

I'd recommend to create org.testng.IMethodInterceptor as a Listener. TestNG calls intercept method just before test suite starts. You get list of all methods as a parameter and have to return modified/new/etc. list with methods you want to run. See documentation http://testng.org/doc/documentation-main.html#methodinterceptors for more details and examples.

Related

I can't mock static method using Mockito and PowerMockito

I'm having trouble mocking a static method in a third-party library. I keep receiving a null-pointer exception when running the test, but I'm not sure why that is.
Here is the class and the void method that invokes the static method I'm trying to mock "MRClientFactory.createConsumer(props)":
public class Dmaap {
Properties props = new Properties();
public Dmaap() {
}
public MRConsumerResponse createDmaapConsumer() {
System.out.println("at least made it here");
MRConsumerResponse mrConsumerResponse = null;
try {
MRConsumer mrConsumer = MRClientFactory.createConsumer(props);
System.out.println("made it here.");
mrConsumerResponse = mrConsumer.fetchWithReturnConsumerResponse();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mrConsumerResponse;
}
}
Below is the test that keeps returning a null-pointer exception. The specific line where the null-pointer is being generated is: MRClientFactory.createConsumer(Mockito.any(Properties.class));
#RunWith(PowerMockRunner.class)
#PrepareForTest(fullyQualifiedNames = "com.vismark.PowerMock.*")
public class DmaapTest {
#Test
public void testCreateDmaapConsumer() {
try {
Properties props = new Properties();
PowerMockito.mockStatic(MRClientFactory.class);
PowerMockito.doNothing().when(MRClientFactory.class);
MRClientFactory.createConsumer(Mockito.any(Properties.class));
//MRClientFactory.createConsumer(props);
Dmaap serverMatchCtrl = new Dmaap();
Dmaap serverMatchCtrlSpy = spy(serverMatchCtrl);
serverMatchCtrlSpy.createDmaapConsumer();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please follow this example carefully: https://github.com/powermock/powermock/wiki/MockStatic
Especially you are missing a
#PrepareForTest(Dmaap.class)
…to denote the class which does the static call.

How to check if an object has at least one field that is not null?

I have a set of beans that are generated by a third-party library.
How can I check if each bean has at least one field that is not null?
The problem is easily solved using reflection. Just add this method to your bean:
public boolean hasAtLeastOneNonEmpty() {
Class<? extends QueryBean> class1 = this.getClass();
Field[] fields = class1.getDeclaredFields();
for (Field field : fields) {
try {
if (field.get(this) != null) {
return true;
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}

Get class from bounded type

I'm learning java generics and I don't know the right way to accomplish this problem.
I have a Bean class:
public class Bean<C> {
protected Dao<C, Integer> getDao(Context context)
{
Dao<C, Integer> dao;
try {
dao = DatabaseHelper.getInstance(context).getDao(); //HERE
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The method getDao() expects as argument a Class<T>. When I simply place the C type, it doesn't work (even with C.class).
What should I do?
Thanks.
Problem solved with another parameter on my method:
protected Dao<C, Integer> getDao(Context context, Class<C> clazz)
{
Dao<C, Integer> dao;
try {
dao = DatabaseHelper.getInstance(context).getDao(clazz);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

NoSuchMethodException loading Build.getRadioVersion() using reflection

I'm trying to load the radio version of the Android device using reflection. I need to do this because my SDK supports back to API 7, but Build.RADIO was added in API 8, and Build.getRadioVersion() was added in API 14.
// This line executes fine, but is deprecated in API 14
String radioVersion = Build.RADIO;
// This line executes fine, but is deprecated in API 14
String radioVersion = (String) Build.class.getField("RADIO").get(null);
// This line executes fine.
String radioVersion = Build.getRadioVersion();
// This line throws a MethodNotFoundException.
Method method = Build.class.getMethod("getRadioVersion", String.class);
// The rest of the attempt to call getRadioVersion().
String radioVersion = method.invoke(null).toString();
I'm probably doing something wrong here. Any ideas?
Try this:
try {
Method getRadioVersion = Build.class.getMethod("getRadioVersion");
if (getRadioVersion != null) {
try {
String version = (String) getRadioVersion.invoke(Build.class);
// Add your implementation here
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.wtf(TAG, "getMethod returned null");
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
What Build.getRadioVersion() actually does is return the value of gsm.version.baseband system property. Check Build and TelephonyProperties sources:
static final String PROPERTY_BASEBAND_VERSION = "gsm.version.baseband";
public static String getRadioVersion() {
return SystemProperties.get(TelephonyProperties.PROPERTY_BASEBAND_VERSION, null);
}
According to AndroidXref this property is available even in API 4. Thus you may get it on any version of Android through SystemProperties using the reflection:
public static String getRadioVersion() {
return getSystemProperty("gsm.version.baseband");
}
// reflection helper methods
static String getSystemProperty(String propName) {
Class<?> clsSystemProperties = tryClassForName("android.os.SystemProperties");
Method mtdGet = tryGetMethod(clsSystemProperties, "get", String.class);
return tryInvoke(mtdGet, null, propName);
}
static Class<?> tryClassForName(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
return null;
}
}
static Method tryGetMethod(Class<?> cls, String name, Class<?>... parameterTypes) {
try {
return cls.getDeclaredMethod(name, parameterTypes);
} catch (Exception e) {
return null;
}
}
static <T> T tryInvoke(Method m, Object object, Object... args) {
try {
return (T) m.invoke(object, args);
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getTargetException());
} catch (Exception e) {
return null;
}
}

In Java Invoking a method using Reflection is not able to find method, when method has baseclass as parameter

Below is the code snippet, I am trying to invoke the usingClass method using REFLECTION. Calling the usingClass() method directly(w/o reflection) works when I pass an object of type Child, though when I try to achieve the same thing using Reflection it throws NoSuchMethodFoundException. Would like to understand if I am missing something or is there any logic behind this? Please help
package Reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestMethodInvocation {
/**
* #param args
*/
public static void main(String[] args) {
TestMethodInvocation test = new TestMethodInvocation();
Child child = new Child();
Parent parent = (Parent)child;
Class<? extends Parent> argClassType = parent.getClass();
Class<? extends TestMethodInvocation> thisClassType = test.getClass();
test.usingClass(child);
Method methodToCall;
try {
methodToCall = thisClassType.getDeclaredMethod("usingClass", argClassType);
methodToCall.invoke(test, parent);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void usingClass(Parent p){
System.out.println("UsingClass: " + p.getClass());
}
}
Output is as below.
UsingClass: class Reflection.Child
java.lang.NoSuchMethodException: Reflection.TestMethodInvocation.usingClass(Reflection.Child)
at java.lang.Class.getDeclaredMethod(Unknown Source)
at Reflection.TestMethodInvocation.main(TestMethodInvocation.java:20)
The reason your code does not work is that getClass() is dynamically bound. Casting to Parent does not affect the runtime type of your object and so the variables child and parent contain the same class object.
Unless you explicitly query your instance for its parent class via getGenericSuperclass() or something similar, you will have to use the static way mentioned by dystroy.
You should use
methodToCall = thisClassType.getDeclaredMethod("usingClass", Parent.class);
because the precise exact class of parent (which is Child), is used at runtime and the type of the variable holding it changes nothing.
Another (too heavy) way to solve it would be :
Class<? extends Parent> argClassType2 = (new Parent()).getClass();
...
methodToCall = thisClassType.getDeclaredMethod("usingClass", argClassType2);

Categories

Resources