Why I can't detect annotations from a loaded java class? - java

I have a plugin within i want to access to the class list of my model package from my maven project. Until now i just did this to load the classes into the plugin :
try {
runtimeClasspathElements = project.getRuntimeClasspathElements();
} catch (DependencyResolutionRequiredException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URL[] runtimeUrls = new URL[runtimeClasspathElements.size()];
for (int i = 0; i < runtimeClasspathElements.size(); i++) {
String element = (String) runtimeClasspathElements.get(i);
try {
runtimeUrls[i] = new File(element).toURI().toURL();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
newLoader = new URLClassLoader(runtimeUrls,
Thread.currentThread().getContextClassLoader());
try { class=newLoader.loadClass("com.pkl.bc.personnaldata.model.Personne");
if(class!=null)
System.out.println(class.getCanonicalName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Until here i can see the full name of my class.
System.out.println(class.getDeclaredFields());
System.out.println(class.isAnnotationPresent(EditColumn.class));
for (Field f : class.getDeclaredFields()) {
EditColumn v = f.getAnnotation(EditColumn.class);
if (v != null) {
System.out.println(v.tableName());
System.out.println(v.oldName());
}
}
but i don't get anything, here is the output :
[Ljava.lang.reflect.Field;#398f573b
false
I also tried to use refelctions
Reflections reflections = new Reflections("com.pkl.bc.personnaldata.model.Personne");
Set<Field> annotated = reflections.getFieldsAnnotatedWith(EditColumn.class);
System.out.println(annotated);
this give me an empty list.
here is my annotation :
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.FIELD})
public #interface EditColumn {
String oldName() default "";
String newName() default "";
String tableName() default "";
}
the annotated field :
#EditColumn(newName = "main_adress", oldName = "adress", tableName = "Personne")
private String main_adress;

I fixed my answer,that your problem is loading different class instance in different ClassLoader when Thread.getContextClassLoader() returns null,because URLClassLoader(urls,parent) when parent is null.you can see the tests that both ways java return a Proxy instance for Annotation Name instance.occurs this problem often someone calls Thread.currentThread().setContextClassLoader(null) in somewhere.so you can solve the problem by checking the contextLoader whether is null.for example:
ClassLoader context=Thread.currentThread().getContextClassLoader();
if(context==null){
context=getClass().getClassLoader();
}
URLClassLoader loader=new URLClassLoader(urls,context);
Test
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Stream;
import static java.lang.String.format;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
/**
* Created by holi on 3/24/17.
*/
public class AnnotationsTest {
private interface StubClass {
Class<?> stubClass() throws ClassNotFoundException;
default <T extends Annotation> T annotation(Class<T> type) throws Exception {
return stubClass().getAnnotation(type);
}
default Annotation[] annotations() throws Exception {
return stubClass().getAnnotations();
}
}
private static final StubClass JAR_WITHIN_ANNOTATION_CLASS = jar("stubs-within-annotation-class.jar");
private static final StubClass JAR_WITHOUT_ANNOTATION_CLASS = jar("stubs-without-annotation-class.jar");
public static StubClass jar(String jar) {
URL jarFile = Objects.requireNonNull(ClassLoader.getSystemResource(jar), format("Jar file not found:%s", jar));
return () -> {
ClassLoader context = Thread.currentThread().getContextClassLoader();
return new URLClassLoader(new URL[]{jarFile}, context).loadClass("Stub");
};
}
private ClassLoader original;
#BeforeEach
void setUp() throws Throwable {
original = Thread.currentThread().getContextClassLoader();
}
#AfterEach
void tearDown() throws Throwable {
Thread.currentThread().setContextClassLoader(original);
}
#Test
void getAnnotationFromJarClassesWillReturnsContextLoaderAnnotationSharedInstanceIfContextLoaderAssociatedWithRuntimeClassLoader() throws Throwable {
Set<Object> annotationsCreated = new HashSet<>();
Set<Object> stubClassCreated = new HashSet<>();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
Stream.of(JAR_WITHIN_ANNOTATION_CLASS, JAR_WITHOUT_ANNOTATION_CLASS).forEach(asserts(stub -> {
Name it = stub.annotation(Name.class);
assertThat(it, is(instanceOf(Name.class)));
assertThat(it.value(), equalTo("stub"));
annotationsCreated.add(it);
stubClassCreated.add(stub.stubClass());
}));
assertThat(annotationsCreated, hasSize(1));
assertThat(stubClassCreated, hasSize(2));
}
#Test
void getAnnotationFromJarClassesWillReturnsNullIfNoContextLoaderAssociated() throws Throwable {
Thread.currentThread().setContextClassLoader(null);
Stream.of(JAR_WITHIN_ANNOTATION_CLASS, JAR_WITHOUT_ANNOTATION_CLASS).forEach(asserts(it -> {
//create different class instance in each class loader
assertThat(it.stubClass().getName(), equalTo("Stub"));
assertThat(it.annotation(Name.class), is(nullValue()));
}));
assertThat(JAR_WITHOUT_ANNOTATION_CLASS.annotations(), is(emptyArray()));
assertThat(JAR_WITHIN_ANNOTATION_CLASS.annotations(), arrayWithSize(1));
Annotation it = JAR_WITHIN_ANNOTATION_CLASS.annotations()[0];
assertThat(it.annotationType(), is(not(instanceOf(Name.class))));
assertThat(it.annotationType().getName(), equalTo(Name.class.getName()));
assertThat(it.annotationType().getDeclaredMethod("value").invoke(it), equalTo("stub"));
}
private interface Assert<T> {
void assertThat(T value) throws Exception;
}
private <T> Consumer<T> asserts(Assert<T> executor) {
return (value) -> {
try {
executor.assertThat(value);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
RuntimeException wrappedException = new RuntimeException(e);
wrappedException.setStackTrace(e.getStackTrace());
throw wrappedException;
}
};
}
}
#Name Annotation
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Created by holi on 3/24/17.
*/
#Retention(RetentionPolicy.RUNTIME)
public #interface Name {
String value();
}
Stub class
#Name("stub")
public class Stub{
}

You are already retrieving the class with its annotations , but you just need to add a loop to itirate all the annotations for each field you have.
try this example , it will print the annotation name and its values when it is available for a field of the loaded class.
for (Field f : loadedClass.getDeclaredFields()) {
System.out.println(f.getName());
for (Annotation a : f.getAnnotations()) {
System.out.println("## SHOWING ANNOTATION FOR FIELD:" + f.getName());
System.out.println(a.toString());
}
}
You can parse the toString to retrieve the values on that annotation.
Waiting for you feedback.

Related

when invoking a java method by method.invoke() its not returning any value instead print in the console log

Hello please help me to find a solution for this problem, I'm creating an web compiler for java programs I have implemented the java inbuilt compiler class to compile the code and its also giving the output but it's giving output in the console and I want that output in the return object or some string variable so I can display the output in front. I'm attaching full code.
package online_compiler.web;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class compiler {
public static void myMethod(String name) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
int result;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
String program = "public class Main{" + " public static void main (String [] args){"
+ " System.out.println (\"Hello, World\");"
+ " }" + "}";
JavaSourceFromString jsfs = new JavaSourceFromString("Main", program);
Iterable<? extends JavaFileObject> fileObjects = Arrays.asList( jsfs);
java.util.List<String> options = new ArrayList<String>();
options.add("-d");
options.add("C:\\Program Files\\Java\\jdk-12.0.2\\bin");
options.add( "-classpath");
URLClassLoader urlClassLoader =
(URLClassLoader)Thread.currentThread().getContextClassLoader();
StringBuilder sb = new StringBuilder();
for (URL url : urlClassLoader.getURLs()) {
sb.append(url.getFile()).append(java.io.File.pathSeparator);
}
sb.append("C:\\\\Program Files\\\\Java\\\\jdk-12.0.2\\\\bin");
options.add(sb.toString());
StringWriter output = new StringWriter();
boolean success = compiler.getTask( output, null, null, options, null, fileObjects).call();
if(success) {
name = output.toString();
System.out.print(output);
java.io.File root = new java.io.File("C:\\\\Program Files\\\\Java\\\\jdk-12.0.2\\\\bin");
URLClassLoader classLoader;
try {
classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
Object obj = null;
Class<?> cls = Class.forName("Main", true, classLoader);
try {
obj = cls.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Method m = cls.getMethod("main", new Class[] { String[].class });
Object[] _args = new Object[] { new String[0] };
Object retobj = m.invoke(obj, _args);
System.out.println(retobj);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//logger.info( LOG_PREFIX + "Class has been successfully compiled");
} else {
//throw new Exception( "Compilation failed :" + output);
}
}
static Iterable<JavaSourceFromString> getJavaSourceFromString(String code) {
final JavaSourceFromString jsfs;
jsfs = new JavaSourceFromString("code", code);
return new Iterable<JavaSourceFromString>() {
public Iterator<JavaSourceFromString> iterator() {
return new Iterator<JavaSourceFromString>() {
boolean isNext = true;
public boolean hasNext() {
return isNext;
}
public JavaSourceFromString next() {
if (!isNext)
throw new NoSuchElementException();
isNext = false;
return jsfs;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
}
class JavaSourceFromString extends SimpleJavaFileObject {
final String code;
JavaSourceFromString(String name, String code) {
super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.code = code;
}
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
The main driver code is this
enter image description here
output in the console log
I have tried many things searching on internet but nothing worked. I want that output in an object or a string variable so I can use that output or that string to front end.
The method you call is static void main. It doesn't return any value.
If you create a method that actually returns something, it should work better

Mock getInstance() of a singleton to return child class (Quarkus)

I am trying to mock getInstance() of a singleton class below to return a mocked class instead:
Base class (passo9() is the method to be mocked):
package br.com.bb.ids.robo.passo09;
import br.com.bb.ids.robo.passo09.dao.RoboSkipDao;
import br.com.bb.ids.robo.passo09.exceptions.RoboSkipDaoFindException;
import br.com.bb.ids.robo.passo09.exceptions.RoboSkipDaoMergeException;
import br.com.bb.ids.robo.passo09.models.RoboSkip;
import javax.enterprise.context.ApplicationScoped;
#ApplicationScoped
public class Motor {
private static Motor instance;
public static Motor getInstance() {
if (instance == null) {
instance = new Motor();
}
return instance;
}
private Motor() {}
/**
* Method to be mocked
*
* #return error code (0 if successful)
* #throws Exception any non expected exception
*/
public int passo9() throws Exception {
try {
System.out.println("Verifica o ponto onde o robô parou");
RoboSkipDao rsDao = RoboSkipDao.getInstance();
RoboSkip rs = rsDao.findByPasso(9);
int resultadoPasso = Integer.parseInt(rs.getValor());
rs.setValor(Integer.toString(resultadoPasso + 32768));
rsDao.merge(rs);
}
catch (RoboSkipDaoFindException e) {
System.out.println("Erro ao consultar registro em robo_skip, passo = 9.");
e.printStackTrace();
return 2;
}
catch (NumberFormatException e) {
System.out.println("Número do registro inválido em robo_skip, passo 9.");
e.printStackTrace();
return 3;
}
catch (RoboSkipDaoMergeException e) {
System.out.println("Erro ao atualizar registro em robo_skip, passo 9.");
e.printStackTrace();
return 8;
}
return 0;
}
}
The extended class to be called instead of Motor above:
package br.com.bb.ids.robo.passo09;
import io.quarkus.test.Mock;
import javax.enterprise.context.ApplicationScoped;
#Mock
#ApplicationScoped
public class MotorMock extends Motor {
public MotorMock(Motor m) {}
#Override
public int passo9() throws Exception {
System.out.println("passo9() mockado - return 0");
return 0;
}
}
The Quarkus main class (Motor.getInstance() should return MotorMock instead of Motor in my test below):
package br.com.bb.ids.robo.passo09;
import io.quarkus.runtime.Quarkus;
import io.quarkus.runtime.annotations.QuarkusMain;
#QuarkusMain
public class Main {
public static void main(String[] args) {
if (args.length != 1 || !args[0].matches("true|false")) {
System.err.println("Indicação em desenvolvimento (true/false) obrigatória.");
return;
}
boolean emDesenvolvimento = Boolean.parseBoolean(args[0]);
System.out.println("Iniciando aplicação...");
try {
Motor motor = Motor.getInstance();
motor.setEmDesenvolvimento(emDesenvolvimento);
int returnCode = motor.passo9();
System.out.println("Finalizando aplicação...");
Quarkus.asyncExit(returnCode);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
My test module:
package br.com.bb.ids.robo.passo09;
import io.quarkus.test.junit.QuarkusMock;
import io.quarkus.test.junit.QuarkusTest;
import javax.inject.Inject;
import org.junit.jupiter.api.Test;
#QuarkusTest
public class MainTest {
#Inject
Motor motor;
#Test
public void testMain() {
MotorMock mm = new MotorMock(Motor.getInstance());
Mockito.when(((Motor)mm).getInstance()).thenReturn(mm);
QuarkusMock.installMockForType(mm, Motor.class);
System.out.println("Testando Main.main(args)...");
String[] args = new String[1];
args[0] = "true";
Main.main(args);
System.out.println("Testes com Main.main(args) efetuados com sucesso.");
}
}
I want to call MotorMock.passo9() instead of Motor.passo9() inside my test case. How do I achieve this? If possible, share with code example.

Reload class which is loaded using custom classloader

The following is my custom classloader class. I set this as default classloader with the following javaargs.
-Djava.system.class.loader=MyCustomClassLoader
import java.io.*;
public class MyCustomClassLoader extends ClassLoader {
public MyCustomClassLoader() { super(); }
public MyCustomClassLoader(ClassLoader parent) { super(parent); }
protected Class loadClass(String name, boolean resolve ) throws ClassNotFoundException {
Class c = super.loadClass(name, resolve );
System.out.println( "name: " + name + ", class: " + c);
return c;
}
}
At this moment, all the classes are loaded with the above custom classloader class when I start server. I wish to update/reload class definition of classes that are part of a particular package (e.g. com.test) on demand. How can I do it?
You should make a class loader which will load custor classes by itself, dont let super load them. Try my example, it may help understand
package test;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
class MyClassLoader extends ClassLoader {
private Map<String, Class<?>> loadedClasses = new HashMap<>();
private String dir;
public MyClassLoader(String dir) throws MalformedURLException {
this.dir = dir;
}
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class<?> c = findLoadedClass(name);
if (c != null) {
return c;
}
c = loadedClasses.get(name);
if (c != null) {
return c;
}
try {
String path = dir + name.replace(".","/") + ".class";
byte[] bytes = Files.readAllBytes(Paths.get(path));
c = defineClass(name, bytes, 0, bytes.length, null);
if (resolve) {
resolveClass(c);
}
return c;
} catch (IOException ex) {
return super.loadClass(name, resolve);
}
}
}
public class ChildFirstClassLoader {
public static void main(String[] args) throws Exception {
ClassLoader cl1 = new MyClassLoader("target/classes/");
Object x1 = cl1.loadClass("test.X1").newInstance();
System.out.println(x1.getClass().getClassLoader());
cl1 = null;
ClassLoader cl2 = new MyClassLoader("target/classes/");
x1 = cl2.loadClass("test.X1").newInstance();
System.out.println(x1.getClass().getClassLoader());
}
}

NullPointerException in Custom ClassLoader - Can't find zipEntry

I'm making a classloader which can take a jar, and based on that, it can take a package name, and is allowed to load only classes that are in that package. When I try to load a class from there I get the error :
Exception in thread "main" java.lang.NullPointerException
at com.classloader.CustomClassLoader.getClassBytes(CustomClassLoader.java:64)
at com.classloader.CustomClassLoader.getClass(CustomClassLoader.java:48)
at com.classloader.CustomClassLoader.loadClass(CustomClassLoader.java:89)
at com.classloader.TestJar.main(TestJar.java:46)
Even though the package name and entry name are correct. Any ideas where the problem is and how to fix it ? The code is below and I believe it's pretty self explanatory.
CustomLoader
package com.classloader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
public class CustomClassLoader extends ClassLoader implements LoaderConstraints {
private Map<String, Class> loaded = new HashMap<String, Class>();
private Map<String, String> available = new LinkedHashMap<String, String>();
private Set<String> allowed = new LinkedHashSet<String>();
public Set<String> getPermited() {
return allowed;
}
public Map<String, String> getAvailable() {
return available;
}
public Map<String, Class> getLoaded() {
return loaded;
}
public CustomClassLoader() {
super(CustomClassLoader.class.getClassLoader());
}
private Class<?> getClass(String className, String pack) throws ClassNotFoundException {
Class<?> c = null;
String classPath = className.replace('.', File.separatorChar) + ".class";
byte[] b = null;
try {
b = getClassBytes(classPath, pack);
c = defineClass(className, b, 0, b.length);
resolveClass(c);
return c;
} catch (IOException e) {
e.printStackTrace();
}
return c;
}
private byte[] getClassBytes(String classPath, String pack) throws IOException {
ZipFile zip = new ZipFile(pack);
// System.out.println(classPath); classPath is right , as well as pack
ZipEntry entry = zip.getEntry(classPath);//This return null, for some reason ???
InputStream in = zip.getInputStream(zip.getEntry(classPath));
long size = entry.getSize();
byte buff[] = new byte[(int)size];
in.read(buff);
in.close();
return buff;
}
#Override
public Class<?> loadClass(String className) throws ClassNotFoundException {
Class<?> found = null;
if(loaded.get(className) != null){
return loaded.get(className);
}
if(available.get(className ) != null){
if(allowed.contains(className ) == true){
found = getClass(className, available.get(className));
if(found != null)
loaded.put(className, found);
}
}
else{
found = super.loadClass(className);
if(found != null)
loaded.put(className, found);
}
return found;
}
public void files(ZipFile zip, Map<String,String> list) throws ZipException, IOException{
Enumeration<? extends ZipEntry> entries = zip.entries();
while(entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
String className = entry.getName().replace('/', '.');
list.put(className.substring(0, className.length() - ".class".length())
,zip.getName());
}
}
}
public void addJar (File jarFile) {
try {
files(new ZipFile(jarFile), available);
} catch (ZipException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void deleteJar(File jarFile) {
Map<String,String> removes = new HashMap<String, String>();
try {
files(new ZipFile(jarFile), removes );
} catch (ZipException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
available.keySet().removeAll(removes.keySet());
}
public void allowPackage(final String p) {
for(String s : available.keySet()){
if(s.startsWith(p))
allowed.add(new String(s));
}
}
public void denyPackage(final String p) {
Set<String> newPermited = new HashSet<String>();
for(String s : allowed){
if(!s.startsWith(p))
newPermited.add(new String(s));
}
allowed = newPermited;
}
}
Test
public static void main(String[] args) throws ZipException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
CustomClassLoader ccl = new CustomClassLoader();
ccl.addJar(new File("derby.jar"));
ccl.allowPackage("org.apache.derby.jdbc");
//System.out.println(ccl.getAvailable().get("org.apache.derby.jdbc.EmbeddedDriver")); --> returns "derby.jar"
Class<?> clazz = ccl.loadClass("org.apache.derby.jdbc.EmbeddedDriver");//Gives exception , line 46
System.out.println(clazz.getClass());
Object instance = clazz.newInstance();
System.out.println(instance.getClass());
}
The derby.jar is located in the project folder. Any help is welcomed :)
Try to replace File.separatorChar with '/'

How to call a method in another class using robotium

Using Robotium for my Android automation I find myself creating the same steps for each test case.
I always need to "Login" and "Logout", I've been trying to create a FunctionsTestClass so I can simply call rLogin(); and rLogout();
Here is an example:
Adding my complete files.
'package com.myproject.mobile.test;
import android.test.ActivityInstrumentationTestCase2;
import android.app.Activity;
import junit.framework.AssertionFailedError;
import com.bitbar.recorder.extensions.ExtSolo;
import com.jayway.android.robotium.solo.By;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
'public class Logout extends ActivityInstrumentationTestCase2<Activity> {
private static final String LAUNCHER_ACTIVITY_CLASSNAME = "com.myproject.mobile.MainActivity";
private static Class<?> launchActivityClass;
static {
try {
launchActivityClass = Class.forName(LAUNCHER_ACTIVITY_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private static ExtSolo solo; // ExtSolo is an extension of Robotium Solo that helps
// collecting better test execution data during test
// runs
#SuppressWarnings("unchecked")
public Logout() {
super((Class<Activity>) launchActivityClass);
}
#Override
public void setUp() throws Exception {
super.setUp();
solo = new ExtSolo(getInstrumentation(), getActivity(), this.getClass()
.getCanonicalName(), getName());
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
solo.tearDown();
super.tearDown();
}
public static void logginin() throws Exception {
try {
//enter username
solo.sleep(17000);
throw e;
} catch (Exception e) {
solo.fail(
"com.myproject.mobile.test.MainActivityTest.testRecorded_scr_fail",
e);
throw e;
}
}
}'
Adding my second file
package com.mypackage.mobile.test;
import android.test.ActivityInstrumentationTestCase2;
import android.app.Activity;
import junit.framework.AssertionFailedError;
import com.bitbar.recorder.extensions.ExtSolo;
import com.jayway.android.robotium.solo.By;
import com.mypackage.mobile.test.*;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
'public class Test extends ActivityInstrumentationTestCase2<Activity> {
private static final String LAUNCHER_ACTIVITY_CLASSNAME = "com.mypackage.mobile.MainActivity";
private static Class<?> launchActivityClass;
static {
try {
launchActivityClass = Class.forName(LAUNCHER_ACTIVITY_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private static ExtSolo solo; // ExtSolo is an extension of Robotium Solo that helps
// collecting better test execution data during test
// runs
#SuppressWarnings("unchecked")
public Test() {
super((Class<Activity>) launchActivityClass);
}
#Override
public void setUp() throws Exception {
super.setUp();
solo = new ExtSolo(getInstrumentation(), getActivity(), this.getClass()
.getCanonicalName(), getName());
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
solo.tearDown();
super.tearDown();
}
public void testRecorded() throws Exception {
try {
Logout.logginin();
} catch (AssertionFailedError e) {
solo.fail(
"com.mypackage.name.MainActivityTest.testRecorded_scr_fail",
e);
throw e;
} catch (Exception e) {
solo.fail(
"com.mypackage.name.MainActivityTest.testRecorded_scr_fail",
e);
throw e;
}
}
}
Updated the bottom two code to reflect my project.
Don't create testcase with name testLoggingin() . Instead of that creat a class having function login(). So that, whenever its needed you can import it and can call the function to login. And you can check conditions using assert.

Categories