how to call android activity from standard java code? - java

This is my sample test project which tests android calculator using robotium.
I want to create jar file of this project but while creating it, it shows error as below:
"Error: Could not find or load main class TestMain".
I think its showing this error becouse there is no main class in that i.e. it couldn't find "public static void main(String args[])". what should i do to overcome this problem?
package com.testcalculator;
import com.jayway.android.robotium.solo.Solo;
import android.test.ActivityInstrumentationTestCase2;
#SuppressWarnings("unchecked")
public class TestCal extends ActivityInstrumentationTestCase2
{
private static final String TARGET_PACKAGE_ID="com.calculator";
private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME="com.calculator.Main";
private static Class launcherActivityClass;
static
{
try
{
launcherActivityClass=Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
}
catch (ClassNotFoundException e)
{
throw new RuntimeException(e);
}
}
public TestCal()throws ClassNotFoundException
{
super(launcherActivityClass);
}
private Solo solo;
#Override
protected void setUp() throws Exception
{
solo = new Solo(getInstrumentation(),getActivity());
}
public void testDisplayBlackBox()
{
solo.enterText(0, "10");
solo.enterText(1, "20");
solo.clickOnButton("Multiply");
assertTrue(solo.searchText("200"));
}
#Override
public void tearDown() throws Exception
{
solo.finishOpenedActivities();
}
}

Related

Error java.lang.NoSuchMethodError In java

I have problems with these methods.
The error is:
Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: pkgModelo.AnalizadorLexico: method <init>()V not found
The classes are:
Class frmAnalizador:
package pkgVista;
import pkgModelo.AnalizadorLexico;
public class frmAnalizador extends javax.swing.JFrame {
AnalizadorLexico alexico;
String linea;
JFileChooser abrirArchivo;
public frmAnalizador() {
initComponents();
alexico = new pkgModelo.AnalizadorLexico();
}
}
In object alexico show the exception.
Class AnalizadorLexico:
package pkgModelo;
import java.io.FileInputStream;
public class AnalizadorLexico implements AnalizadorLexicoConstants {
public AnalizadorLexico() {
}
public static void principal(FileInputStream file) throws ParseException {
try {
AnalizadorLexico analizador = new AnalizadorLexico(file);
analizador.Algoritmo();
System.out.println("El analizador l\u00e9xico ha compilado correctamente");
}
catch(ParseException e) {
System.out.println("Hay errores: " + e.getMessage());
}
}
}
Here in this line AnalizadorLexico analizador = new AnalizadorLexico(file); you passed file object as a parameter where as your class AnalizadorLexico has not any kind of parameterized constructor so you have to make one more constructor which has a parameter of FileInputStream.
public AnalizadorLexico(FileInputStream file){
//Your Code
}

com.calculator cannot be resolved to a type

For automating application using robotium i have use this code.
package com.calculator.test;
import android.test.ActivityInstrumentationTestCase2;
import com.robotium.solo.Solo;
public class TestMain extends ActivityInstrumentationTestCase2 {
private Solo solo;
public TestMain() {
super(com.calculator, Main.class);
}
#Override
protected void setUp() throws Exception {
super.setUp();
solo = new Solo(getInstrumentation(), getActivity());
}
public void testDisplayBlackBox() {
// Enter 10 in first editfield
solo.enterText(0, "10");
// Enter 20 in first editfield
solo.enterText(1, "20");
// Click on Multiply button
solo.clickOnButton("Multiply");
// Verify that resultant of 10 x 20
assertTrue(solo.searchText("200"));
}
#Override
protected void tearDown() throws Exception {
solo.finishOpenedActivities();
}
}
But eclipse is showing error in
public TestMain() {
super(com.calculator, Main.class);
...
}
for com.calculator and Main as "Cannot be resolved to a type".
Is there any imports needed to avoid this error?
The doc here: http://developer.android.com/reference/android/test/ActivityInstrumentationTestCase2.html says the first paramater of the constructor should be a String.
Your code should be
public TestMain() {
super("com.calculator", Main.class);
}
In which package is defined the class Main? Is it visible from you code?

ThreadWeaver always throws IllegalArgumentException

I am trying to use Google ThreadWeaver to write a unit test for concurrent code. No matter what I do, I will get an IllegalArgumentException. I am still working with an example, but even that does not work. This is what I tried:
public class ExampleTest {
public static class ExampleMain implements MainRunnable<Example> {
private Example example;
#Override
public Class<Example> getClassUnderTest() {
return Example.class;
}
#Override
public String getMethodName() {
return null;
}
#Override
public Method getMethod() throws NoSuchMethodException {
return null;
}
#Override
public void initialize() throws Exception {
example = new Example();
}
#Override
public Example getMainObject() {
return example;
}
#Override
public void terminate() throws Exception {
}
#Override
public void run() throws Exception {
example.test("second");
}
}
public static class ExampleSecondary implements SecondaryRunnable<Example, ExampleMain> {
private ExampleMain exampleMain;
#Override
public void initialize(ExampleMain main) throws Exception {
exampleMain = main;
}
#Override
public void terminate() throws Exception {
}
#Override
public boolean canBlock() {
return false;
}
#Override
public void run() throws Exception {
exampleMain.getMainObject().test("main");
}
}
public static class Example {
private List<String> list = new ArrayList<String>();
public String test(String s) {
System.out.println("1" + s);
list.add(s);
System.out.println("2" + s);
return list.get(0);
}
}
#Test
public void testThreadWeaver() throws Exception {
ClassInstrumentation instrumentation = Instrumentation.getClassInstrumentation(Example.class);
Method tested = Example.class.getDeclaredMethod("test", String.class);
Method breakpoint = List.class.getDeclaredMethod("add", Object.class);
CodePosition codePosition = instrumentation.afterCall(tested, breakpoint);
InterleavedRunner.interleave(new ExampleMain(), new ExampleSecondary(), Arrays.asList(codePosition)).throwExceptionsIfAny();
}
}
The stack trace says:
java.lang.IllegalArgumentException: Class Example is not instrumented
at
com.google.testing.threadtester.CallLoggerFactory.getClassInstrumentation(CallLoggerFactory.java:108)
at
com.google.testing.threadtester.Instrumentation.getClassInstrumentation(Instrumentation.java:65)
at MyTest.testThreadWeaver(MyTest.java:92
I followed the instructions at the official Google code webpage, but it does not seem to work. Any ideas?
ThreadWeaver needs to instrument your classes in order to add breakpoints to your methods. Therefore, you cannot run the tests with JUnit directly but you must run your test from a specific test runner. For your case this would be ThreadedTestRunner. The actual test methods must then be annotated with #ThreadedTest instead of #Test. This should work:
#Test
public void startTest() throws Exception {
new ThreadedTestRunner().runTests(getClass(), Example.class);
}
#ThreadedTest
public void testThreadWeaver() throws Exception {
// here comes your test
}

Function works in main class but not it test class

I have a class which compiles and runs as expected (adds one test node per execution):
public class ReqsDb {
private final String STORE_DIR;
public GraphDatabaseService graphDb;
private static enum RelTypes implements RelationshipType {
IDENTIFIES, SATIFIES
}
public ReqsDb(String dbPath) {
STORE_DIR = dbPath;
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(STORE_DIR);
registerShutdownHook(graphDb);
}
public void createTestNode() {
Transaction tx = graphDb.beginTx();
Node newNode;
try {
newNode = graphDb.createNode();
newNode.setProperty("test", "test");
tx.success();
} finally {
tx.finish();
}
}
private static void registerShutdownHook(final GraphDatabaseService graphDb) {
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
graphDb.shutdown();
}
});
}
void shutDown() {
graphDb.shutdown();
}
public static void main(String[] args) {
ReqsDb testDb = new ReqsDb("target/testDb");
testDb.createTestNode();
}
}
However the test function, testCreateTestNode() causes error:
java.lang.RuntimeException: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.StoreLockerLifecycleAdapter#4e3a2be1' was successfully initialized, but failed to start.
Since the function works as called from main(), I think there is something wrong with the test class.
package com.github.dprentiss;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class ReqsDbTest extends TestCase {
protected ReqsDb testDb = new ReqsDb("target/testDb");
public ReqsDbTest(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(ReqsDbTest.class);
}
public void testDbService() {
assertNotNull(testDb);
}
public void testCreateTestNode() {
testDb.createTestNode();
}
public void tearDown() {
testDb.shutDown();
}
Is there something wrong with my test set up?
Try to put
protected ReqsDb testDb = new ReqsDb("target/testDb");
in an init method . Follow this example:
Is there a basic template I can use to create a test?

How to abstract Robotium Setup to run multiple test files

In a Blackbox test environment I would need to include CODE 1 and end with CODE 2 to perform a test by running Android JUnit Test (as explained from the Robotium site):
CODE 1:
public class ConnectApp extends ActivityInstrumentationTestCase2 {
private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME="com.example.android.notepad.NotesList";
private static Class<?> launcherActivityClass;
private Solo solo;
static {
try { launcherActivityClass=Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME); }
catch (ClassNotFoundException e) { throw new RuntimeException(e); }
}
public ConnectApp() throws ClassNotFoundException {
super(launcherActivityClass);
}
public void setUp() throws Exception {
this.solo = new Solo(getInstrumentation(), getActivity());
}
CODE 2:
public void testNumberOne() { … }
public void testNumberTwo() { … }
}
However, I would like to abstract CODE 1 of the code ( which includes getInstrumentation() and getAcitvity()) so that I can simply call them in a separate test file and then run CODE 2 . This is because I want to have tests in separate files and don't want to keep adding the same amount of CODE 1 code but just call a method/constructor to initiate the process.
Is there a way to do this? Thank you in advance.
yes there is a way to do this. What you will need to do is create an empty test class such as:
public class TestTemplate extends ActivityInstrumentationTestCase2 {
private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME="com.example.android.notepad.NotesList";
private static Class<?> launcherActivityClass;
private Solo solo;
static {
try { launcherActivityClass=Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME); }
catch (ClassNotFoundException e) { throw new RuntimeException(e); }
}
public ConnectApp() throws ClassNotFoundException {
super(launcherActivityClass);
}
public void setUp() throws Exception {
super.setUp();//I added this line in, you need it otherwise things might go wrong
this.solo = new Solo(getInstrumentation(), getActivity());
}
public Solo getSolo(){
return solo;
}
}
Then for every test class you want in the future instead of extending ActivityInstrumentationTestCase2 you will extend TestTemplate.
for example:
public class ActualTest extends TestTemplate {
public ActualTest() throws ClassNotFoundException {
super();
}
public void setUp() throws Exception {
super.setUp();
//anything specific to setting up for this test
}
public void testNumberOne() { … }
public void testNumberTwo() { … }
}

Categories