I am making an android game with the libGDX Java game library. I would like to test my code but not quite sure how to go about it. I have set up testing and run sample tests like.
public class UnitTestExample {
#Test
public void oneEqualsOne() {
assertEquals(1, 1);
}
}
Now how do I test a function like
public void addListenerToExitButton(){
buttonExit.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {Gdx.app.exit();
}
});
}
This function adds a LibGDX event to a button called buttonExit (In this case, the event is to exit the game.)
I use JMockIt for unit testing for my LibGdx projects and it works like a charm.
For your case, I assume the method you want to test is in a screen class, in other words, that is the class you are testing. Therefore you need to mock up all dependencies of this class and then instantiate it.Again I assume that button instance would be a private member of that class. So, under normal circumstances, you can not access it from your test code. JMockit can help you with that:
TextButton buttonToTest = (TextButton) Deencapsulation.getField(yourScreenUnderTest, "yourButtonName");
buttonToTest.toggle();
Above code will get the button and emulate click event on it. In this context, Gdx.app is a dependency and you already have mocked it up. What it means that, when your button is clicked, your mock instance will expect and exit call without any parameters. So, if you add this to your expectations, you are done.
Simple and elegant =]
Related
public class Something {
private static Something something = new Something();
public static Something get(){
return something;
}
private EventQueueWindow eventQueue;
private Something(){
TopComponent tc = WindowManager.getDefault().findTopComponent("EventQueueWindow");
eventQueue = (EventQueueWindow) tc;
}
EventQueue getQueue(){
return eventQueue;
}
}//end class Something
Now I want to write a JUnit test which requires the ability to access eventQueue.
public void testgetQueue() {
Something something = Something.get();
assertEquals("Failed to return EventQueueWindow",something.getQueue().getClass(), EventQueueWindow.class);
}
I get a java.lang.NullPointerException when I run the test because eventQueue has a null value despite it being assigned a value in class Something's constructor. I've read around that this may have something to do with components being handle in a different thread or not being initialized before the test is run. But I'm pretty new to java and unit testing and don't know how to solve this problem. Any guidance would be appreciated.
Your biggest problem is that you have global state. Global state is generally poor programming, including with tests.
Testing for particular implementation class, probably isn't a very good test.
I suggest removing your global state and dependency upon the global state that you are lumbered with from your libraries, then test that.
I believe what is going on is that the class is designed to exist inside a large context. WindowManager gives the class access to that context but the context does not exist in the unit test therefore the manager returns null.
One solution is to have two overloads of the constructor with one taking the WindowManger as an argument. Then in the test pass a mocked WindowManager to this constructor.
Mocking example via Mockito:
WindowManager man = Mockito.mock(WindowManager.class);
EventQueueWindow window = Mockito.mock(EventQueueWindow.class);
Mockito.when(man.findTopComponent("EventQueueWindow")).thenReturn(window);
The section on GWT testing describes how to verify output of Presenter in Display object, but does not explain how to do the other way around. In other words, I want to check whether Presenter will make a correct request to RPC Service when a user clicks button in Display.
How can I simulate button click in Display? Firing GWT events is not straightforward, as they have protected constructors. Is there a way to do it simply, without subclassing ClickEvent class?
#Before
protected void setUp() {
mockRpcService = mock(NegotiationServiceAsync.class);
eventBus = new HandlerManager(null);
mockDisplay = mock(NegotiationPresenter.Display.class);
negotiationPresenter = new NegotiationPresenter(mockRpcService,
eventBus, mockDisplay);
}
#Test
private void testSth() {
when(mockDisplay.getSuppliersEmails()).thenReturn("address#domain.com");
when(mockDisplay.getTaskDescription()).thenReturn("This is the task to do");
// This does not work
mockDisplay.getSubmitButton().fireEvent(new ClickEvent());
verify(mockRpcService).startTask(any(NegotiationRequest.class), any(AsyncCallback.class));
}
When you use MVP you normally test methods in the presenter injecting a mocked implementation of the view, so in your test the display does nothing, just offers stub methods to the presenter.
In the other hand, your real display implementation should delegate all actions to the presenter.
The way to test the behavior of your presenter when a user clicks on the submit button is calling the method in the presenter, something like this:
#Test
private void testSth() {
when(mockDisplay.getSuppliersEmails()).thenReturn("address#domain.com");
when(mockDisplay.getTaskDescription()).thenReturn("This is the task to do");
negotiationPresenter.onSubmit();
verify(mockRpcService).startTask(any(NegotiationRequest.class),
any(AsyncCallback.class));
}
A very different case is if you wanted to test your code using GWTTestCase so as you could use real view implementations, but in this case your tests would last a long, loosing one of the main goals of using MVP, which is, to decouple the view to test the main app code which is supposed to be in Presenters and classes which can be run in the JVM.
I've created a few minor apps for Android while learning. Being a PHP developer, it's a challenge to get used to it.
I'm especially wondering how I could define a couple of "general" functions in a separate class. Eg I have a function that checks if network connection is available, and if not, shows a dialog saying that the user should enable it. Currently, that function exists in several of my activities. Of course that seems strange - I suppose it would be more logical to define it once and include it in the activites where needed.
I tried putting it in a new class, and included that class in the original activity. But that failed since eg getBaseContext() is not accepted anymore.
I'm wondering how to go ahead. What should I be Google-ing for ? What is this mechanism called?
You need to create class with static methods. Like this
public class HelperUtils {
public static void checkNetworkConnection(Context ctx) {...}
}
Then you can call it from any place like this:
HelperUtils.checkNetworkConnection(this.getContext());
Assuming current class has Context.
You should read books on general OOP concepts where different type of methods are explained.
You can for example create a class - let's call it NetworkUtils. In this class you can create static method boolean isNetworkConnectionAvailable() and return true if is available and false otherwise. In this class you can create another static method void showNoConnectionDialog(Activity activity) - and in this method you create dialog starting with
public static void showNoConnectionDialog(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//setting message, listener etc. and finally
builder.create().show();
}
In your activity, where you want to check and handle network connection you should call:
if (!NetworkUtils.isConnectionAvailable(getApplicationContext())) {
NetworkUtils.showNoConnectionDialog(YourActivityClassName.this)
}
I guess this should work.
The selenium tests I'm gonna be doing are basically based on three main steps, with different parameters. These parameters are passed in from a text file to the test. this allows easy completion of a test such as create three of "X" without writing the code to do the create three times in one test.
Imagine i have a test involving creating two of "X" and one of "Y". CreateX and CreateY are already defined in separate tests. Is there a nice way of calling the code contained in createX and createY from say, Test1?
I tried creating a class with the creates as seperate methods, but got errors on all the selenium.-anything-, ie every damn line. it goes away if i extend seleneseTestCase, but it seems that my other test classes wont import from a class that extends seleneseTestCase. I'm probably doing something idiotic but i might as well ask!
EDIT:
well for example, its gonna be the same setUp method for every test, so id like to only write that once... instead of a few hundred times...
public void ready() throws Exception
{
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://localhost:9443/");
selenium.start();
selenium.setSpeed("1000");
selenium.setTimeout("999999");
selenium.windowMaximize();
}
thats gonna be used EVERYWHERE.
its in a class called reuseable. Id like to just call reuseable.ready(); from the tests SetUp... but it wont let me....
public class ExampleTest {
#Before
public void setup() {
System.out.println("setup");
}
public void someSharedFunction() {
System.out.println("shared function");
}
#Test
public void test1() {
System.out.println("test1");
someSharedFunction();
}
#Test
public void test2() {
System.out.println("test2");
someSharedFunction();
}
}
The contents of the function after the #Before annotation is what will be executed before every test. someSharedFunction() is an example of a 'reusable' function. The code above will output the following:
setup
test1
shared function
setup
test2
shared function
I would recommend using JUnit and trying out some of the tutorials on junit.org. The problem you have described can be fixed using the #Before annotation on a method that performs this setup in a super class of your tests
What is the simplest way to make sure the listener's update has even been called ?
Update: I am testing the Listener (not the Subject) and once update is called, the test pass.
d.addServiceComponentChangeListener(new ServiceComponentChangeListener() {
//In the Unittest, I want to make sure this has been called
public void notifyChange(ServiceComponentChangeEvent event) {
System.out.println("#notifyChange");
}
});
Even if the listener does not implement an interface, you can still create a mock for it using something like Mockito. Using runtime code insertion, inspection of the class to be mocked, and purple pixie dust, it can impersonate other classes. At my company most unit tests use either Mockito (the newer ones) or EasyMock (the older ones) so we're sure we're testing JUST the one class.
I question your statement "Update: I am testing the Listener (not the Subject)", though. If your test is verifying the listener gets called, you're testing the thing that's supposed to call the listener, not listener itself. So which is it?
If the listener implements the interface you can make a mock class that implements the listener. Then you can design this mock to fit your testing. If it does not implement an interface, as long as the listeners class is not final, you could extend it.
I would test it by replace the call System.out or whatever that section should really do with an interface that be later mocked and use behavior verification to make sure it was called. So...
public class d
{
private MessageDisplayer m_UserDisplay;
public d()
{
m_UserDisplay = new DisplaySystemOut()
}
public d(MessageDisplayer AllowsSensing)
{
m_UserDisplay = AllowsSensing;
}
//blah blah blah....
d.addServiceComponentChangeListener(new ServiceComponentChangeListener()
{
public void notifyChange(ServiceComponentChangeEvent event) {
m_UserDisplay.DisplayMessage("#notifyChange");
}
});
}
Now you can mock MessageDisplayer in your test and make sure it is called and that the parameter was equal to "#notifyChange"