I have util class with one method:
public static void setStyleForWidgetLayout(HTMLPanel panel, int rowQuantity) {
Which for each Widget in HTMLPannel assign widgth depends on number of widgets and rows.
It is very simple switch.
I want to test this method but when i create test with normal JUnit test case i recieve error on creating HTMLPanel.
Caused by: java.lang.UnsupportedOperationException: ERROR: GWT.create() is only usable in client code! It cannot be called, for example, from server code. If you are running a unit test, check that your test case extends GWTTestCase and that GWT.create() is not called from within an initializer or constructor.
Next I tried to extend GWTTestCase but it requires to implement getModuleName() but i dont have any particular module because the class I test is just util class
Ok, I thought, lets mock it. I used mockito, but the errror occured, same as from previous code section.
Than I found class GwtTestWithMockito and tried to run this and again I recieved error.
com.googlecode.gwt.test.exceptions.GwtTestConfigurationException: No declared module. Did you forget to add your own META-INF/gwt-test-utils.properties file with a 'gwt-module' property in the test classpath?
I added #GWTModule and this META-INF/gwt-test-util.properties. And experimented with different configurations. I tried existing module names and not existing ones but still i recieve error above.
Thanks in advance
I'm afraid you have to use GWTTestCase. Your module name is the name of your module XML file.
Sometimes you have to add your Panel to the root panel, I generally do this just to be on the safe side.
Related
I want to pass a dynamic parameter to a test case from testng xml, my parameter is something like:
String dynamicParameter=generateRandomStringForMail();
Here is my testcase:
#Test()
public void customerCreatorAllProducts () throws Exception {
setup();
Functions.pages.LoginPage login = PageFactory.initElements(driver, Functions.pages.LoginPage.class);
login.navigateRegisterPage().createFixedPasswordCustomerRequiredFields(dynamicParameter);
}
I will be using this parameter in other cases as well, how can i do this from testng.xml or with something else?
I am not familiar with testing.xml, but Mockito immediately comes to mind for this: http://mockito.org.
add Mockito to your project (e.g. through the build.gradle page)
add the import to your test file:
import static org.mockito.Mockito.*;
within your test class, create a mock of the class which has the generateRandomStringForMail() method. In my current project, I have
DefaultFileService mockFileService = mock(DefaultFileService.class);
define what you want the method to return under these test conditions, e.g.
when(mockFileService.generateRandomFileName()).thenReturn("fileName");
Whenever your tests need to use the result of the method in question, you can use "fileName", because you have told the test environment to give this response. My project has a method to update the image file associated with an inventory item, which process includes using the DefaultFileService to generate a random file name, then passing the image file and the new file name to the DefaultFileService to save the file in the system. My test code can't see or guess what file name would actually be produced, but my 'when' line above has resolved that problem for the purposes of testing my QuiltController class:
quiltController.update(data, mockFile);
verify(mockFileService).save(mockFile, "fileName"); // confirms the save() method was called with the expected parameters
It feels pretty similar to what you are trying to do, so hopefully that helps you proceed if you do want to explore Mockito. Don't be surprised if you need to refactor some of your work to make it more testable. I did, and have better code as a result. Give it a go :)
I am referencing PlayerUtil.getMovementSpeed(player); in my Speed class, and in my PlayerUtil class, I have the method defined as:
public static double getMovementSpeed(Player player) {
//my code here
}
But whenever the getMovementSpeed method is referenced in my other classes, it throws this error:
java.lang.NoSuchMethodError: net.Swedz.util.PlayerUtil.getMovementSpeed(Lorg/bukkit/entity/Player;)D
I thought it may be that Eclipse was exporting incorrectly, but I rebooted it and tried again with no avail.
EDIT: I did try decompiling the exported jar, and the public static double getMovementSpeed(Player player) method does exist in the exported jar.
EDIT: My friend is also having a similar issue, and is using IntelliJ, so Eclipse is not the issue.
EDIT: Class definition for PlayerUtil:
package net.Swedz.util;
public class PlayerUtil implements Listener {
//getMovementSpeed is defined in here
}
Class definition for Speed:
package net.Swedz.hack.detect.move;
public class Speed implements Hack, Listener {
//my detection methods and method containing PlayerUtil.getMovementSpeed(player);
}
SOLUTION: I found on my own that I had classes conflicting between two plugins on my server. I had one jar with net.Swedz.util.PlayerUtil and another with net.Swedz.util.PlayerUtil both with different contents. I added my project name in all lower case after the net.Swedz and it seems to have fixed it!
Thanks!
This is a very simple to troubleshoot.
you have used that method and you were able to compile that class which uses this method.
so that means at compile time it reefers the class PlayerUtil which has this method.
But runtime class loader has loaded the class PlayerUtil which doesn't contain this method.
now what you have to do is just find out where that class has been loaded from (at run time)
if you can recreate the problem while it is running using eclipse/IDEA follow these steps.
(if it runs in in application server or standalone application, then start the application server or application with debug enabled.and you can do remote debug from your IDE).
put a break-point where exception was thrown (where you call this method).
start to debug , it will hit the break-point.
then evaluate this expression PlayerUtil.class.getResource("PlayerUtil.class")
4.you can find the path where the class was loaded from.
now you have two options , decompile the class and check whether that method is these (same return type, same name , same args).
or in debug , you can evaluate PlayerUtil.class.getDeclaredMethods() to find out.
So you can solve the problem by rectifying the class path entries if it was loaded from a wrong place.
My problem is that when class B tries to use A.check() my execution stops due to a java.lang.NoClassDefFoundError.
So here is my class configuration. NB: the classes are in the same packages and I have already checked that the A.class file is placed where it should be.
public class A{
// vars
// declare some public method
public synchronized static boolean check(){
//do stuff, log some info and return boolean
}
}
public class B implements Runnable{
public void run() {
A.check();
}
}
And here is my stacktrace:
java.lang.NoClassDefFoundError:
org/mypackage/A
at org/mypackage.B.run()
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException:
org/mypackage.B
at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
The project is really big and class A is used lots of times before this call without any problem, so i don't think that is something relative to the classpath. Note that this is part of the last call of the software that should close up everything.
Moreover, I have two maven goals: the first one execute the questioned code without any problem, instead the second rise this error every time.
So I have solved my problem and I post here the solution so maybe can be useful for someone else.
First of all the error: java.lang.NoClassDefFoundError
This error is really different from ClassNotFoundException and this is where I'have lost a lot of time.
NoClassDefFoundError in Java is raised when JVM is not able to locate a particular class at runtime which was available at compile time. For example, if we have a method call from a class accessing any member of a Class and that class is not available during runtime then JVM will throw NoClassDefFoundError. It’s important to understand that this is different than ClassNotFoundException which comes while trying to load a class at run-time only and the name was provided during runtime, not on compile time. Many Java developer mingles this two Error and gets confused. Here I quote a really useful blog that I uesd.
So in a shorter way NoClassDefFoundError comes if a class was present during compile time but not available in java classpath during runtime.
But even with those information the problem was still there until I found the mystery: one of the reason that can place the class in a state that can be compiled but not located at runtime is that if you have static initialization that fail (e.g. in my class I had as field a static variable instantiated badly).
So remember to check for you initialization phase if you have static variables in your class this could be the reason of your java.lang.NoClassDefFoundError.
By the way I don't get why this kind of error is not raising some more meaninful errors for example java.lang.ExceptionInInitializerError or something like that.
Try to debug maven execution by running: mvn -X <your_goals>
It would be useful to see your POM file.
If you are working with spring mvc and if you made bean entry in dispatche-servlet.xml for Controller class.
Example :
<bean id="MyClass" class="com.aaps.myfolder.MyClass">
<property name="methodNameResolver">
<ref bean="methodNameResolver" />
</property>
</bean>
And if MyClass.java is not compiled & if no class file is generated in classes folder of your project folder then it wil show java.lang.NoClassDefFoundError.
So check whether the MyClass.class is created or not in classes folder if you are working with spring mvc.
Does Class A have anything that is done in a static block. You can get this exception even if a class is being loaded and static blocks fails for any reason reason. try to put in logging to see if something like this is happening.
i have a play 2.3 application that I want to test.
This application has a Global.java class that extends GlobalSettings in order to start a recurring Akka task every 5minutes.
During testing I don't want the task to be scheduled since it creates several issues and I don't need it.
Therefore I would like to override the GlobalSettings.
By reading the documentation, it looks like it should be possible to use a FakeApplication for that. However I tried to do that in several ways and the framework still runs my default global settings.
I created a base class for my tests that looks like this:
public class BaseTest
extends WithApplication
{
protected FakeApplication provideFakeApplication()
{
return fakeApplication(inMemoryDatabase("test"), new GlobalSettings());
}
}
According to the documentation, if a test class extends WithApplication a fake application should automatically start for me, with the configuration provided.
Disregarding if this happens or not, even before the testing methods are called, the default global settings trigger. The "new Global()" doesn't override the default.
I also tried to manually start the fakeApplication using a #BeforeClass annotation, with no success.
I am running the tests with the "activator test" command.
It looks like that the fakeApplication is indeed used for each test, but before even the first test starts, the main application is started and its global triggered. And that's what I don't want it to happen.
Am I doing something wrong or is it a bug in play? if it is a bug, is there a workaround?
EDIT: I just noticed that even the database settings don't get overridden correctly. I normally use a h2 file database for developing, but i want a inmemory, different one for testing. However by using the code above doesn't change the database used, and therefore my tests run against my file DB.
I also tried something like this:
#Test
public void testMyTest()
{
running(fakeApplication(inMemoryDatabase("test2")), () -> {
//TESTING CODE THAT USES DB
});
}
and still any query inside the body runs against the DB configured in the config file, not the inmemory database.
Edit
Chafik solution kind of worked for me, since by specifying a different config file in the build.sbt file I managed to override my settings. Things are still really wierd though:
1)Now if from my fakeApplication constructor I try to override the GlobalSettings by passing a new instance in helper method, the settings are correctly overridden, while before I could not at all override the main one
2)If I revert my change and don't supply a test conf file, I can still override the globalsettings. That is, the behaviour is different than it used to be initially.
Something is definitely strange around the test command, its configuration, running scope, and the way fakeApplication override the configuration, and/or the documentation about it si definitely unclear and lacking. However since at least I achieved what I wanted to do I'll still consider the answer solved.
I did what you want like this.
Set a different config file for testing in your build.sbt
javaOptions in Test += "-Dconfig.file=conf/application.test.conf"
Create conf/application.test.conf
Include main configuration file at the beginning include "application.conf"
Override the settings that you want
Create a property like this startAkkaActor=true in the main config file
Create a property like this startAkkaActor=false in the test config file
Update you Global.java where you start your Akka actor
if (Play.application().configuration().getBoolean("startAkkaActor")) {
// Start your Akka actor
}
You can do the same with your database settings
The config file must be defined in build.sbt because Play forks JVM for each test without duplicating the parameters set in the main JVM. The following does not work :
activator test -Dconfig.file=conf/application.test.conf
I am using Struts 2 to create a web application. I am using StrutsTestCase for Junit test case to test the Action class. I have imported struts2-junit-plugin-2.3.4.jar as I am using struts2-core-2.3.4.jar. Inside the testcase method, when i tried to set the request parameters, request variable is not available for use. it is showing compilation error. I am getting 'request cannot be resolve' error. In my test class i am extending StrutsTestCase which has request as protected parameter. But it is not available inside extended method.
My test action looks like this:
import org.apache.struts2.StrutsTestCase;
public class WallPlanningActionTest extends StrutsTestCase {
public void testList() {
request.setParameter("salesOrg",1);
}
You can only get compilation errors if StrutsTestCase which your class is extended is not org.apache.struts2.StrutsTestCase. You could optimize the imports or just use FQCN.
public class WallPlanningActionTest extends org.apache.struts2.StrutsTestCase {
For future readers:
I had the same problem - the protected request field was not accessible. The problem was that i hadn't add the spring libraries. StrutsTestCase uses spring-core-x.y.z and spring-test-x.y.z. It is depended on them an i couldn't find a way to use the unit tests without them.
Other dependencies could be found by opening the struts-junit-plugin jar (as archive). Open the META-INF folder and in there you will find DEPENDENCIES file with a list of all dependencies.
Hope this helps someone.