PowerMocking static does not return expected object - mockito

I have a problem mocking Calendar.getInstance(). As you now this method returns a Calendar - the object I am mocking.
Right now my code looks like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Calendar.getInstance() gets called various times in surveillance.checkDatabase() and every time it is a new object and not the expected mock of Calendar.
Can anyone see what I am doing wrong?

It seems that you need to add the target test class in the PrepareForTest tag:
#PrepareForTest({ Calendar.class, Surveillance.class })
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Calendar.class, Surveillance.class })
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Even Tom Tresansky's example above will need it if we move the Surveillance class to somewhere outside MockCalendarTest class.

I'm not as familiar with the when(object.call()).andReturn(response); but I'm assuming it works the same way as expect.(object.call()).andReturn(response);. If that is the case, then it looks like all you are missing a replay of the class PowerMock.replay(Calendar.class) and you are trying to do a full static mock instead of a partial static mock. This should resolve your issue.
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
PowerMock.mockStaticPartial(Calendar.class, "getInstance"); //Mock Static Partial
expect(Calendar.getInstance()).andReturn(calendar);
PowerMock.replay(Calendar.class); // note the replay of the Class!
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
//Whatever tests you need to do here
}
}

It seems like you're doing everything right. For instance, this test below passes, proving that the Calendar returned by Calendar#getInstance() is in fact the one you set up with the static mocking.
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class MockCalendarTest {
#Test
public void testFailingDatabase() {
mockStatic(Calendar.class);
final Calendar testCalendar = new GregorianCalendar();
testCalendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(testCalendar);
final Surveillance surveillance = new Surveillance();
final Calendar resultCalendar = surveillance.checkDatabase();
assertTrue(testCalendar == resultCalendar);
}
public static class Surveillance {
public Calendar checkDatabase() {
return Calendar.getInstance();
}
}
}
Perhaps post the relevant parts of the Surveillance class so we can see how it's trying to get a new Calendar and assess why it's failing.

Related

PowerMockito calls real method on Mocked Object when defining second "when" clause

I am trying to define some different mocked behaviours when a method is called with different parameters. Unfortunately, I find that the second time I try to mock the given method on a (mocked) class, it runs the actual method, causing an exception because the matchers are not valid parameters. Anyone know how I can prevent this?
manager = PowerMockito.mock(Manager.class);
try {
PowerMockito.whenNew(Manager.class).withArguments(anyString(), anyString())
.thenReturn(manager);
} catch (Exception e) {
e.printStackTrace();
}
FindAuthorityDescriptionRequestImpl validFindAuthorityDescription = mock(FindAuthorityDescriptionRequestImpl.class);
PowerMockito.when(manager.createFindAuthorityDescriptionRequest(anyString(), anyString())).thenCallRealMethod();
PowerMockito.when(manager.createFindAuthorityDescriptionRequest(Matchers.eq(VALID_IK),
Matchers.eq(VALID_CATEGORY_NAME))).thenReturn(validFindAuthorityDescription);
PowerMockito.when(manager.processRequest(Matchers.any(FindAuthorityDescriptionRequest.class)))
.thenThrow(ManagerException.class);
PowerMockito.when(manager.processRequest(Matchers.eq(validFindAuthorityDescription)))
.thenReturn(generateValidAuthorityDescriptionResponse());
The following code is a working example based on your mock setup (I've added dummy classes to make it runnable).
The code also contains asserts to verify that the mocked methods return expected values. Also, the real method createFindAuthorityDescriptionRequest is only called once.
Note: This was tested with `powermock 2.0.7` and `mockito 2.21.0`.
If issues persist, I'd suggest checking if the real method is not additionally called from somewhere else in your program (other than the code quoted in your problem statement).
package com.example.stack;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.*;
import static org.powermock.api.mockito.PowerMockito.mock;
#RunWith(PowerMockRunner.class)
#PrepareForTest(fullyQualifiedNames = "com.example.stack.*")
public class StackApplicationTests {
private static final String VALID_IK = "IK";
private static final String VALID_CATEGORY_NAME = "CATEGORY_NAME";
private static final Object VALID_RESPONSE = "RESPONSE";
#Test
public void test() {
Manager manager = mock(Manager.class);
try {
PowerMockito.whenNew(Manager.class).withArguments(anyString(), anyString())
.thenReturn(manager);
} catch (Exception e) {
e.printStackTrace();
}
FindAuthorityDescriptionRequestImpl validFindAuthorityDescription = mock(FindAuthorityDescriptionRequestImpl.class);
PowerMockito.when(manager.createFindAuthorityDescriptionRequest(anyString(), anyString())).thenCallRealMethod();
PowerMockito.when(manager.createFindAuthorityDescriptionRequest(eq(VALID_IK), eq(VALID_CATEGORY_NAME)))
.thenReturn(validFindAuthorityDescription);
PowerMockito.when(manager.processRequest(any(FindAuthorityDescriptionRequest.class)))
.thenThrow(ManagerException.class);
PowerMockito.when(manager.processRequest(eq(validFindAuthorityDescription)))
.thenReturn(VALID_RESPONSE);
// verify that the mock returns expected results
assertEquals(Manager.REAL_RESULT, manager.createFindAuthorityDescriptionRequest("any", "any"));
assertEquals(validFindAuthorityDescription, manager.createFindAuthorityDescriptionRequest("IK", "CATEGORY_NAME"));
assertThrows(ManagerException.class, new ThrowingRunnable(){
#Override
public void run( ) {
manager.processRequest(new FindAuthorityDescriptionRequestImpl());
}
});
assertEquals(VALID_RESPONSE, manager.processRequest(validFindAuthorityDescription));
}
}
interface FindAuthorityDescriptionRequest {}
class FindAuthorityDescriptionRequestImpl implements FindAuthorityDescriptionRequest {}
class ManagerException extends RuntimeException {}
class Manager {
public static FindAuthorityDescriptionRequestImpl REAL_RESULT = new FindAuthorityDescriptionRequestImpl();
public Manager(String s1, String s2) {}
public FindAuthorityDescriptionRequest createFindAuthorityDescriptionRequest(String ik, String category) {
return REAL_RESULT;
}
public Object processRequest(FindAuthorityDescriptionRequest request) {
return null;
}
}

Junit for QueryDsl

I'm trying to write a test case for a query dsl, I'm getting null pointer exception when I run the test case
Dsl Class
QMyClass myClass= QMyClass.myClass;
queryFactory = new JPAQueryFactory(em);
JPAQuery<?> from = queryFactory.from(myClass);
JPAQuery<?> where = from
.where(prepdicates);
orderBy(orderSpecifier).offset(sortOrder.getOffset())
.limit(sortOrder.getPageSize());
**Junit test case:**
import javax.inject.Provider;
import javax.persistence.EntityManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.data.jpa.repository.support.QueryDslRepositorySupport;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.JPQLTemplates;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
#RunWith(PowerMockRunner.class)
public class MyClass{
#Mock
QueryDslRepositorySupport queryDslRepositorySupport;
#Mock
EntityManager entityManager;
#Mock
JPAQueryFactory queryFactory;
#Mock
JPAQuery step1;
#InjectMocks
MyClass myClass;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
Provider<EntityManager> provider = new Provider<EntityManager>() {
#Override
public EntityManager get() {
return entityManager;
}
};
queryFactory = new JPAQueryFactory(JPQLTemplates.DEFAULT, provider);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Test
public void sampleTest() throws Exception {
QMyClass class= Mockito.mock(QMyClass.class);
Mockito.when(queryFactory.from(class)).thenReturn(step1);
Predicate step2 = Mockito.mock(Predicate.class);
Mockito.when(step1.where(step2)).thenReturn(step1);
OrderSpecifier step3 = Mockito.mock(OrderSpecifier.class);
Mockito.when(step1.orderBy(step3)).thenReturn(step1);
Mockito.when(step1.offset(Mockito.anyLong())).thenReturn(step1);
Mockito.when(step1.limit(Mockito.anyLong())).thenReturn(step1);
myClass.method("");
}
}
When I run this test case I'm getting null pointer exception at line number 2 in sampleTest() method. I googled but did't find any article for this, not sure why this NE, even after mocking the queryfacotry
Here is the trace :
java.lang.NullPointerException
at com.querydsl.core.DefaultQueryMetadata.addJoin(DefaultQueryMetadata.java:154)
at com.querydsl.core.support.QueryMixin.from(QueryMixin.java:163)
at com.querydsl.jpa.JPAQueryBase.from(JPAQueryBase.java:77)
at com.querydsl.jpa.impl.JPAQueryFactory.from(JPAQueryFactory.java:116)
at
As I mentioned in the comment, your problem is that you do not use a mock, but the real object instead.
Remove the queryFactory initialisation from your setup method.
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
Provider<EntityManager> provider = new Provider<EntityManager>() {
#Override
public EntityManager get() {
return entityManager;
}
};
// remove this line
// queryFactory = new JPAQueryFactory(JPQLTemplates.DEFAULT, provider);
}
Also you need to change your implementation, you can not use
queryFactory = new JPAQueryFactory(em); inside your code, as it can not be mocked.
What you could do instead is having a method that returns the JPAQueryFactory,
either from another class - which you can mock -
or in the same method, then you would need to spy on your class instead.
As you didnt add the code for the class you want to test (MyClass - hopefully a different one from the identical named UnitTest?), another possibility would be that you try to use Field or Constructor Injection (as indicated by the use of your annotations), but then there should not be an object creation for the JPAQueryFactory in your code at all.
This also seems to be wrong:
You should inject mocks into your class under test, not in your UnitTest class.
#RunWith(PowerMockRunner.class)
public class MyClass{
...
#InjectMocks
MyClass myClass;

Actor position is incorrect - Libgdx

Please help me, I'm pulling my hair out.
I have a class called "HudBarView" which extends the Group class(scene2d). It takes care of the drawing of the HUD Bar at the top of the screen(Pause button, score, etc).
Another class I have is "HUDManager" which takes care of all the HUD work in the game, including HUD Bar.
These two classes are very short and self-explantory. There is nothing sophisticated.
Now, currently I have only a pause button(ImageButton) in my HUD Bar but the problem is - it is visible only after I resize or pause and then resume the screen.
Here is a gif that describes my problem:
http://i.gyazo.com/6140c4ac1ea0778e4e1afce161ea3dc0.gif
I have tried to play a little bit with the code and I found out that the positioning of the actor is wrong. For instance if I define the position of the button with these values:
Vector2 position = new Vector2(Values.SCREEN_WIDTH-Values.Pause_Width*2,Values.SCREEN_HEIGHT-Values.Pause_Height*2);
Instead of these:
Vector2 position = new Vector2(Values.SCREEN_WIDTH-Values.Pause_Width,Values.SCREEN_HEIGHT-Values.Pause_Height);
It does show up on the screen but at the wrong position and after pause/resume it show up at the correct position.
Here is my HudBarView class:
package views.hud.views;
import views.renderers.HUDManager;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import engine.helpers.AssetsManager;
import engine.helpers.Values;
public class HUDBarView extends Group{
private ImageButton pause;
private HUDManager hud_manager;
private Skin skin;
public HUDBarView(HUDManager hud_manager) {
this.hud_manager = hud_manager;
initiate();
}
private void initiate() {
skin = new Skin(AssetsManager.getAsset(Values.BUTTONS_PACK, TextureAtlas.class));
pause = new ImageButton(skin.getDrawable("pause"));
pause.setSize(Values.Pause_Width, Values.Pause_Height);
pause.setPosition(Values.SCREEN_WIDTH - pause.getWidth(), Values.SCREEN_HEIGHT- pause.getHeight());
addActor(pause);
}
}
HUDManager class:
package views.renderers;
import views.hud.ParticleEffectsActor;
import views.hud.views.HUDBarView;
import aurelienribon.tweenengine.TweenManager;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import engine.helpers.AssetsManager;
import engine.helpers.UIHelper;
import engine.helpers.Values;
public class HUDManager extends Group {
private Stage stage;
private Skin skin;
private Image text;
private HUDBarView hudView;
public HUDManager(Stage stage) {
this.stage = stage;
initiate();
addActor(hudView);
addActor(particles);
}
public void initiate() {
skin = AssetsManager.getAsset(Values.GAME_SKIN_PACK, Skin.class);
hudView = new HUDBarView(this);
particles = new ParticleEffectsActor();
}
public Stage getStage() {
return stage;
}
}
And Here is my game screen problem:
package views.screens;
import views.renderers.GameRenderer;
import views.renderers.HUDManager;
import engine.GameInputHandler;
import engine.GameWorld;
import engine.Values;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.StretchViewport;
/* Created by David Lasry : 10/25/14 */
public class GameScreen extends ScreenWrapper {
private GameWorld world;
private HUDManager hudManager;
private GameRenderer renderer;
private Stage stage;
public GameScreen() {
super();
ScreenHandler.getInstance().getGame().getAssetsManager()
.loadAsstes(2, this);
world = new GameWorld();
stage = new Stage(new StretchViewport(Values.SCREEN_WIDTH,
Values.SCREEN_HEIGHT));
camera = (OrthographicCamera) stage.getCamera();
InputMultiplexer inputs = new InputMultiplexer();
inputs.addProcessor(stage);
inputs.addProcessor(new GameInputHandler(world.getMonkeyManager(),
camera));
Gdx.input.setInputProcessor(inputs);
}
#Override
public void render(float delta) {
switch (state) {
case RUN:
stage.act(delta);
stage.draw();
world.update(delta);
break;
case PAUSE:
break;
}
}
// Callback method that is called when the assets are loaded
#Override
public void assetsLoaded() {
super.assetsLoaded();
renderer = new GameRenderer(world);
hudManager = new HUDManager();
stage.addActor(renderer);
stage.addActor(hudManager);
}
public HUDManager getHudManager() {
return hudManager;
}
#Override
public void dispose() {
stage.dispose();
ScreenHandler.getInstance().getGame().getAssetsManager().unload(2);
}
}
I'm struggling with this problem for almost 3 days and I have no idea what is causing this.
I even opened a new project, duplicated the relevant classes and just tried to position the button at the top right corner of the screen and it worked! So why it doesn't work in my actual game?
Please help !

How can I make Selenium tests inside my JSF project?

I have quite big JSF 1.2 project and I want to write some integration tests to it.
The perfect situation will be, when I can run these tests from my project and it opens my browser and makes all the actions (with Selenium), which are written in my test cases. Ofc opening browser is not required when It will run these tests anyway :)
I've tried a few possibilities, anyway I still can't attach any selenium library to my project and I realized that I just dont know where to start - can you give me some direction?
might help you ,
you can write you test logic inside test method
package com.test;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.fail;
public class test1 {
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new InternetExplorerDriver();
driver = new ChromeDriver();
baseUrl = "http://www.google.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Ignore
#Test
public void test1() throws Exception {
// your test code
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}
you just need call test1 class which you want to test it .
it will be automatically working on it .

How do I get input from a user using j2me canvases? is this even possible?

I am currently trying to learn J2ME and build a connect four game (some of you might know this as 'four in a row'). I've More or less got all of the aspects of my game working, apart from one thing that is driving me mad! This is of course getting the text from the user!
For the two player mode of the game I want to be able to allow each player to enter their name. I am struggling to find a working example of text input that doesn't use the main Midlet.
For example the examples on java2x.com just use a single midlet (no classes or canvases or anything).
As it stands my application's main midlet start method simply opens a main menu class:
package midlet;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import view.*;
public class Main extends MIDlet {
public void startApp() {
MainMenu mm = new MainMenu();
showScreen(mm);
}
public static void showScreen(Displayable screen) {
Display.getDisplay(instance).setCurrent(screen);
}
public void pauseApp() {
}
public static void quitApp() {
instance.notifyDestroyed();
}
public void destroyApp(boolean unconditional) {
}
}
The main menu class is as follows:
package view;
import javax.microedition.lcdui.*;
import lang.*;
import model.*;
import midlet.Main;
public class MainMenu extends List implements CommandListener {
private Command ok = new Command(StringDefs.currDefs.getString("TEXT_OK"), Command.OK, 1);
public MainMenu() {
super(StringDefs.currDefs.getString("TEXT_TITLE"), List.IMPLICIT);
// we we add in the menu items
append(StringDefs.currDefs.getString("TEXT_PLAY1"), null);
append(StringDefs.currDefs.getString("TEXT_PLAY2"), null);
append(StringDefs.currDefs.getString("TEXT_HIGHSCORETABLE"), null);
append(StringDefs.currDefs.getString("TEXT_HELP"), null);
append(StringDefs.currDefs.getString("TEXT_QUIT"), null);
this.addCommand(ok);
this.setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if (c == ok) {
int selectedItem = this.getSelectedIndex();
if (selectedItem != -1) {
switch (selectedItem) {
case 0:
GameBoard gameBoard = new model.GameBoard();
GameCanvasOnePlayer board = new GameCanvasOnePlayer(gameBoard);
Main.showScreen(board);
break;
case 1:
GameBoard gameBoardTwo = new model.GameBoard();
GameCanvasTwoPlayer GameCanvasTwoPlayer = new GameCanvasTwoPlayer(gameBoardTwo);
Main.showScreen(GameCanvasTwoPlayer);
break;
case 2:
HighScores hc = new HighScores();
midlet.Main.showScreen(hc);
break;
case 3:
Help he = new Help();
midlet.Main.showScreen(he);
break;
case 4:
QuitConfirmation qc = new QuitConfirmation();
midlet.Main.showScreen(qc);
break
}
}
}
}
}
When a two player game is selected (case 1 in the above switch) from this menu I would like two text boxes to appear so that I can get both player names and store them.
What would be the best way of going about this? is this even possible with canvases? And do you know where I can find a relevant example or at least something which may help?
You can either:
1. Make the user enter his input in an ugly Textbox (which takes the whole screen)
2. Use the textbox control I've written from scratch a long time ago which is available here
and looks something like this (3 Textfields shown):
I've got a solution! well sort of.
I can create a form without using the main midlet:
The following main class is part of a source package called midlet (much like in my project):
package midlet;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import view.*;
public class Main extends MIDlet {
private static UsernameForm unameForm=new UsernameForm();
private static MIDlet instance;
public void startApp() {
instance=this;
showScreen(unameForm); // show user name form
}
public static String getUsername1() {
return(unameForm.getUsername1());
}
public static String getUsername2() {
return(unameForm.getUsername2());
}
public void pauseApp() {
}
public static void showScreen(Displayable d) {
Display.getDisplay(instance).setCurrent(d); // show next screen
}
public void destroyApp(boolean unconditional) {
}
}
The next bit of code is the username form class that is part of a source package called view:
package view;
import javax.microedition.lcdui.*;
public class UsernameForm extends Form implements CommandListener {
private String username1="";
private String username2="";
private TextField tfUsername1=new javax.microedition.lcdui.TextField("User 1","User1",40,TextField.ANY);
private TextField tfUsername2=new javax.microedition.lcdui.TextField("User 2","User2",40,TextField.ANY);
private Command cmdOK=new Command("OK",Command.OK,1);
public UsernameForm() {
super("User details");
append(tfUsername1);
append(tfUsername2);
addCommand(cmdOK);
setCommandListener(this);
}
public void commandAction(Command cmd,Displayable d) {
if (cmd==cmdOK) {
this.setUsername1(tfUsername1.getString());
this.setUsername2(tfUsername2.getString());
// TO DO, GO TO NEXT SCREEN
}
}
/**
* #return the username1
*/
public String getUsername1() {
return username1;
}
/**
* #param username1 the username1 to set
*/
public void setUsername1(String username1) {
this.username1 = username1;
}
/**
* #return the username2
*/
public String getUsername2() {
return username2;
}
/**
* #param username2 the username2 to set
*/
public void setUsername2(String username2) {
this.username2 = username2;
}
}
So it looks like there's no easy way of doing it using canvases, I think I am better of using 'ugly forms' instead as they should work whatever the device.
That's a really sticky situation. Basically you will need to use J2ME's input text widget (which by the way looks horrible). If you don't, you'll end up having to implement all the logic behind the different types of phone keyboards and you won't have access to the dictionary... Your canvas will basically only be capturing keystrokes, not text input...
Sorry.
Here you need to, implement custom Items, all you need to do is to extend the part of the canvas where to want the user/player to enter his/her name to the CustomItems, and implement the customItems predefined abstract methods, and write method for Key Strokes and that's available in the nokia forum. They have explained it pretty good. Check out the Nokia forum.

Resources