I found great instrumental test tutorial on YT Advanced Android Espresso. I took code from there with small adjustment to my needs.
import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withChild;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.core.AllOf.allOf;
...
#Test
public void checkToolbarTitle() {
String toolbarTitile = getInstrumentation().getTargetContext().getString(R.string.my_bus_stops);
onView(allOf(isAssignableFrom(TextView.class), withParent(isAssignableFrom(Toolbar.class)))).check(matches(withText(toolbarTitile)));
}
Unfortunatelly it does not work for me. Test failed with:
android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: (is assignable from class: class android.widget.TextView and has parent matching: is assignable from class: class android.widget.Toolbar)
What is wrong with it? How can I test it in other way?
This works for me:
onView(allOf(instanceOf(TextView.class), withParent(withId(R.id.toolbar))))
.check(matches(withText("toolbarTitile")));
SOLUTION
The method is fine. As Chiu-Ki Chan wrote in her tutorial you can "pinpoint that one particular view".
BUT you have to make sure you imported proper Toolbar:
import android.support.v7.widget.Toolbar;
instead of:
import android.widget.Toolbar;
Here's an alternative (and more idiomatic approach):
onView(withId(R.id.toolbar)).check(matches(hasDescendant(withText(toolbarTitle))))
If you're using an ActionBar, not a Toolbar, use this:
onView(allOf(instanceOf(TextView.class),
withParent(withResourceName("action_bar"))))
.check(matches(withText("My ActionBar title")));
Note: To quickly add the imports for these methods, put the blinking cursor on the unresolved method, then do Android Studio ➔ Help ➔ Find Action ➔ search for "show context action" or "show intention action" ➔ click on the result option ➔ A popup window will appear ➔ click on "Import static method ...". You can also assign a keyboard shortcut to "Show Context Actions". More info here. Another way is to enable "Add unambiguous imports on the fly" in the Settings.
I don't remember if I wrote this myself, or if I found it somewhere, but this is how I check toolbar titles:
public static Matcher<View> withToolbarTitle(CharSequence title) {
return withToolbarTitle(is(title));
}
public static Matcher<View> withToolbarTitle(final Matcher<CharSequence> textMatcher) {
return new BoundedMatcher<View, Toolbar>(Toolbar.class) {
#Override
public boolean matchesSafely(Toolbar toolbar) {
return textMatcher.matches(toolbar.getTitle());
}
#Override
public void describeTo(Description description) {
description.appendText("with toolbar title: ");
textMatcher.describeTo(description);
}
};
}
This works with all cases. Example assertion: onView(withId(R.id.toolbar)).check(matches(withToolbarTitle("title")));
Related
Maybe what I am trying to do is not worthwhile, it sure feels that way after spending many days on it.
I have A Base Class shown here:
package jimmy.kilmer.com;
import java.awt.Color;
import jarPackageImports.AI;
import jarPackageImports.MovementAction;
import jarPackageImports.Info;
import jarPackageImports.PlayerAction;
public class GameAI extends AI {
public gameAI(Info info) {
super(info);
setJerseyNumber(32);
}
public Color getColor() {
return Color.RED;
}
public String getName() {
return "Usain Bolt";
}
public PlayerAction update() {
// TODO game movement actions
// all available methods not listed here...
info.getVelocity();
info.getX();
info.getY();
MovementAction steeringBehavior = null;
return steeringBehavior;
}
//basically used for testing setup
public int[][] populateAllPossibleNodes() {
int[][] allPossibleNodes = new int[screenWidth/20][screenHeight/20];
return allPossibleNodes;
}
}
I have been given a jar, that sets up the game environment. It uses reflection for the setup. I am not familiar with reflection, unfortunately, as I am more beginner level.
I have read a lot about TDD, and am convinced that can help me stay orderly, and code in a disciplined way. I have some say that TDD is not really useful for Game development, which the arguments may be true, in regard to making an "enjoyable game." But, from a purely coding standpoint, I remain steadfast in my believe that TDD is the way to go. But, that remains to be seen, since it is still theoretical. I would like to try it.
I have installed Junit 5, and have done many tutorials, but it's all pretty basic examples. My particular test case uses reflection, super classes, derived classes, dynamic data. My head is spinning.
My goal is just to get setup such that I can start doing some Test driven development.
Here is my Junit test class:
package jimmy.kilmer.com;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import jarPackageImports.Info;
class GameAITest {
private GameAITest AIObject;
private jarPackageImports.Info info;
#BeforeEach
void setUp() throws Exception {
AIObject = new GameAITest(info);
#AfterEach
void tearDown() throws Exception {
}
#Test
void testPopulateAllPossibleNodes() {
// 1. given/arrange
int[][] array1 = new int[80][65];
// 2. when/act
int[][] array2 = AIObject.populateAllPossibleNodes();
// 3. then/assert
assertArrayEquals(array1, array2);
}
}
That is my best stab so far, but it still get a compile error. Specifically:
java.lang.NullPointerException:Cannot invoke "jarPackageImports.Info.getScene()" because "this.info" is null
In summation:
maybe everything I am trying is rubbish?
Do I need to use dynamic junit testing? I would have to read up on that.
Do I need to mock (use Mockito?) to instantiate an object to test? I would need to read up on that as well.
Is it possible to instantiate an object from GameAI? Do I need to/how would I use relection to do that? class.getConstructors()? And, I would have to read up on that.
thanks in advance.
I am making a Xposed Module that would allow users to modify the message displayed on the lock screen when Wrong pattern, pin or password is entered.
I am following this tutorial.
After digging into the android source code on GitHub, I found out the method that displays the message on the lock screen, that was onPatternChecked() in the class com.android.keyguard.KeyguardPatternView.java. The method uses the kg_wrong_pattern string resource which has the value Wrong Pattern when wrong pattern is drawn.
This is how my class looks like:-
package com.batrashubham.customlockscreenerrormessage;
import android.content.res.XResources;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_InitPackageResources;
/**
* Created by shubham on 19/7/16.
*/
public class CustomErrorMessage implements IXposedHookInitPackageResources,IXposedHookZygoteInit {
#Override
public void initZygote(StartupParam startupParam) throws Throwable {
XResources.setSystemWideReplacement("android","bool","config_unplugTurnsOnScreen",false);
}
#Override
public void handleInitPackageResources(XC_InitPackageResources.InitPackageResourcesParam resparam) throws Throwable {
if(!resparam.packageName.equals("com.android.keyguard")){
return;
}
XposedBridge.log("I just got into your lock screen");
resparam.res.setReplacement("com.android.keyguard", "string", "kg_wrong_pattern", "Nice try.!!");
}
}
The module is showing up in the Xposed Installer app and is successful activated, but still the original message is showing up on the lock screen when I draw a wrong pattern.
I am currently testing it on Android 6.0.1 (CyanogenMod 13).
What am I doing wrong?
I need to port the following Eclipse template to IntelliJ IDEA
/**
* See method name.
*/
#${testType:newType(org.junit.Test)}
public void should${testdesc}() {
// given ${cursor}
${staticImport:importStatic('org.hamcrest.Matchers.*', 'org.junit.Assert.*', 'org.mockito.BDDMockito.*')}
// when
// then
}
What I've got so far is
/**
* See method name.
*/
#org.junit.Test
public void should$EXPR$() {
// given $END$
${staticImport:importStatic('org.hamcrest.Matchers.*', 'org.junit.Assert.*', 'org.mockito.BDDMockito.*')}
// when
// then
}
And then tick the Shorten FQ names flag.
What's the IDEA equivalent for the ${staticImport:importStatic()} expression?
You cannot just import the static imports in a live template. (You can for a file template, see below). But you can when using a method in the template. You just simply fully qualify the class and then select both the "Shorten FQ names" and "Use static import if possible" options. For example, the following:
org.junit.Assert.assertEquals("$END$", $EXPECTED$, $ACTUAL$);
Will result in:
import static org.junit.Assert.*;
. . .
assertEquals("my error message", myExpectedVar, myActualVar);
when invoked. (I have the $EXPECTED$ and $ACTUAL$ variables set to variableOfType("") with corresponding default values expected and actual)
If you want certain static imports to be included in all your unit tests, then I would recommend editing the "Class" File and Code Template. For example:
package ${PACKAGE_NAME};
#if ($NAME.endsWith("Test"))
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.BDDMockito.*;
#end
#parse("File Header.java")
public class ${NAME}
{
#if ($NAME.endsWith("Test"))
// Add any default test methods or such you want here.
#end
}
Keep in mind however, the static import will immediately be removed if you have the "Optimize imports on the fly" option (in IDE Settings > Editor > Auto import) turned on, unless you also include a method (or other code) that makes use of the static import.
Now its possible to add live templates with static imports:
You have to check static import in Options
#org.junit.Test
public void should$EXPR$when$CONDITION$() {
org.junit.Assert.assertThat(null, org.hamcrest.CoreMatchers.is(org.hamcrest.CoreMatchers.nullValue()));
}
I import an existing project into eclipse, and always encountered this problem. First, it appears the error: R cannot be solved. After import android.R. the error turned to the following methods. "start cannot be or is not a field"
I also checked the gen folder, where contains a R.java file. The file looks good, including the following contents: I also tried to clear the project and rebuilt which didnot work. Does any body have any idea how to solve this? Thanks a lot.
R.java:
public static final class layout {
public static final int kbd=0x7f030000;
public static final int main=0x7f030001;
public static final int start=0x7f030002;
}
startactivity.java:
import android.R;
import android.R.layout;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
public class StartActivity extends Activity {
Intent mMain;
/** Called when the activity is first created. */
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);//where error appears**
}
public void onStartButtonClick(View v) {
mMain = new Intent(this, MainActivity.class);
startActivity(mMain);
}
you are importing
android.R
first remove android.R and android.R.layout from import
and import R with your packagename.R
for eg. com.example.R instead of android.R
Try doing Project -> Clean. If that doesn't work it looks like this might have already been answered: R cannot be resolved - Android error
To any one who may face the similar problem with me. I found an answer from the link below:
R cannot be resolved - Android error
My problem was solved by:
1. delete all the imports lines.
2. press ctrl+shift+O to manually regenerate all imports.
And then the problem disappeared.
Many thanks for all the comments above.
Can someone convert this into Clojure, I don't know to do the line setMainWindow(argument) like things....
import com.vaadin.Application;
class something {
public void init() {
Window main = new Window("The Main Window");
setMainWindow(main);
addComponent(new WindowOpener("Window Opener", main));
}
}
Update:
package app;
import com.vaadin.Application;
import com.vaadin.ui.Button;
import com.vaadin.ui.Window;
/**
* The Application's "main" class
*/
#SuppressWarnings("serial")
public class MyVaadinApplication extends Application{
private Window window;
#Override
public void init(){
window = new Window("My Vaadin Application");
setMainWindow(window);
window.addComponent(new Button("Click Me"));
}
}
There is a "/lib/vaadin.jar" which contains all "com.vaadin.*" things.
I think setMainWindow(window); is from the extended class. I am not going to write that method.
Literal translation:
(defn init []
(let [main (Window. "The Main Window")]
(setMainWindow main)
(addComponent (WindowOpener. "Window Opener" main))))
Though it doesn't make much sense without the context.
See http://dev.vaadin.com/wiki/Articles/ClojureScripting. Also I would suggest http://www.odesk.com.