Creating Location Client in Android API 19 - location-client

I have been making an application that saves user location in a string,
First of all I need to Define Location Services Callbacks,
for Connecting the Location Client, I need to create a Location Client in OnCreate() method of my Application,
so I have used the below code as my Main.java File:
As you see, the Location Client function mLocationClient.connect(); is called in OnStart() method of the activity,
and that makes the application to Force Stop.
package ir.superus8r.location3;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.test.suitebuilder.TestSuiteBuilder.FailedToCreateTests;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 0;
LocationClient mLocationClient;
TextView tv01 = (TextView) findViewById(R.id.tvwtf);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
mLocationClient = new LocationClient(this, this, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// TODO Auto-generated method stub
if(connectionResult.hasResolution()){
try{
//activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e){
//error log
e.printStackTrace();
}
} else {
tv01.setText("Unknown Error!");
}
}
#Override
public void onConnected(Bundle dataBundle) {
// TODO Auto-generated method stub
// displaying the connection status
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
mLocationClient.connect();
}
}
Here's the LogCat output:
07-03 07:13:15.557: D/AndroidRuntime(28102): Shutting down VM
07-03 07:13:15.557: W/dalvikvm(28102): threadid=1: thread exiting with uncaught exception (group=0x41b978b0)
07-03 07:13:15.567: E/AndroidRuntime(28102): FATAL EXCEPTION: main
07-03 07:13:15.567: E/AndroidRuntime(28102): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{ir.superus8r.location3/ir.superus8r.location3.MainActivity}: java.lang.NullPointerException
07-03 07:13:15.567: E/AndroidRuntime(28102): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2192)
07-03 07:13:15.567: E/AndroidRuntime(28102): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
07-03 07:13:15.567: E/AndroidRuntime(28102): at android.app.ActivityThread.access$600(ActivityThread.java:150)
07-03 07:13:15.567: E/AndroidRuntime(28102): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1298)
07-03 07:13:15.567: E/AndroidRuntime(28102): at android.os.Handler.dispatchMessage(Handler.java:99)
07-03 07:13:15.567: E/AndroidRuntime(28102): at android.os.Looper.loop(Looper.java:213)
07-03 07:13:15.567: E/AndroidRuntime(28102): at android.app.ActivityThread.main(ActivityThread.java:5225)
07-03 07:13:15.567: E/AndroidRuntime(28102): at java.lang.reflect.Method.invokeNative(Native Method)
07-03 07:13:15.567: E/AndroidRuntime(28102): at java.lang.reflect.Method.invoke(Method.java:525)
07-03 07:13:15.567: E/AndroidRuntime(28102): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
07-03 07:13:15.567: E/AndroidRuntime(28102): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
07-03 07:13:15.567: E/AndroidRuntime(28102): at dalvik.system.NativeStart.main(Native Method)
07-03 07:13:15.567: E/AndroidRuntime(28102): Caused by: java.lang.NullPointerException
07-03 07:13:15.567: E/AndroidRuntime(28102): at android.app.Activity.findViewById(Activity.java:1853)
07-03 07:13:15.567: E/AndroidRuntime(28102): at ir.superus8r.location3.MainActivity.<init>(MainActivity.java:29)
07-03 07:13:15.567: E/AndroidRuntime(28102): at java.lang.Class.newInstanceImpl(Native Method)
07-03 07:13:15.567: E/AndroidRuntime(28102): at java.lang.Class.newInstance(Class.java:1130)
07-03 07:13:15.567: E/AndroidRuntime(28102): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
07-03 07:13:15.567: E/AndroidRuntime(28102): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2183)
07-03 07:13:15.567: E/AndroidRuntime(28102): ... 11 more
Any helps will be appreciated,
Thanks in advance.

You can use the condition while creating locationClient object.
onStart(){
if(mLocationClient==null){
mLocationClient = new LocationClient(this, this, this);
}
mLocationClient.connect();
}
Else if onStart is not compulsary call mLocationClient.connect() in onCreate() itself;

Related

I need help using Jsoup to display the html from a website

very new to coding, using Java writing android application. I have included my code to this point below. At this point I am just trying to get the HTML from a website. I have been googling my way to this point. I do have <uses-permission android:name="android.permission.INTERNET" />in the manifest. I call the code to get the html in the oncreate event (new URLParser). At first I tried to view the html in the logcat, the code is still there for that in the onPostExecute event. The program ran fine this way, but the html did not show up in the verbose section of the logcat. So I added a temporary button and text view to the application. The button's onClick is set to call "showHTML". The app loads up, and when I press the button it crashes. So I cannot seem to see the html in the logcat, or the textview after pressing the button.
package com.example.brewerycruiser;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new URLParser();
}
public void showHTML (View view) {
TextView HTMLview =
view.getRootView().findViewById(R.id.textView);
HTMLview.setText(doc.toString());
}
Document doc = null;
public class URLParser extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
doc = Jsoup.connect("https://www.coloradobrewerylist.com/brewery/").userAgent("Mozilla/5.0").get();
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
Log.v("DATA", doc.toString());
}
}
}
The error log is below:
11-19 18:09:32.779 18293-18293/com.example.brewerycruiser E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.brewerycruiser, PID: 18293
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:402)
at android.view.View.performClick(View.java:5225)
at android.view.View$PerformClick.run(View.java:21195)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
at android.view.View.performClick(View.java:5225) 
at android.view.View$PerformClick.run(View.java:21195) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5451) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.jsoup.nodes.Document.toString()' on a null object reference
at com.example.brewerycruiser.MainActivity.showHTML(MainActivity.java:27)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397) 
at android.view.View.performClick(View.java:5225) 
at android.view.View$PerformClick.run(View.java:21195) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5451) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Any help is greatly appreciated,
Thank you

"java.lang.NullPointerException" when trying to click any element in a page

The code was running completely fine until yesterday. Now, when I am trying to run any test case, Selenium (using Java) throws java.lang.NullPointerException on the homepage itself. Below is a simple test case which is failing due to the error.
Below is my Test class which is calling the constructor of TestBase class and then, initializing the driver object. When the control goes into homepage.clickSearchLink() method, the test ends and error comes.
package com.ss.qa.testcases;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.*;
import com.ss.qa.base.TestBase;
import com.ss.qa.pages.HomePage;
import com.ss.qa.pages.SearchPage;
public class SearchPageTest extends TestBase{
HomePage homepage;
SearchPage searchpage;
SearchPageTest(){
super();
}
#BeforeMethod
public void setUp(){
initialization();
homepage = new HomePage();
searchpage = homepage.clickSearchLink();
}
#Test
public void verifyResultCount() {
int count = searchpage.countResults("a");
Assert.assertEquals(count, 15);
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
Below is my TestBase class which is calling the constructor of Test Base class and initializing the driver object
package com.ss.qa.base;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Driver;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import com.ss.qa.util.TestUtil;
import com.ss.qa.util.WebEventListener;
public class TestBase {
public static WebDriver driver = null;
public static Properties prop;
public static EventFiringWebDriver e_driver;
public static WebEventListener eventListener;
public TestBase(){
try {
prop = new Properties();
FileInputStream ip = new FileInputStream("D:\\Users\\eclipse-
workspace\\src\\main\\java\\com\\ss\\qa\\config\\config.properties");
prop.load(ip);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void initialization() {
String browserName = prop.getProperty("browser");
if (browserName.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Downloads\\"chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
System.out.println("driver=" + driver);
}
else if (browserName.equalsIgnoreCase("FF")) {
System.setProperty("webdriver.gecko.driver", "C:\\Users\\Downloads\\geckodriver-v0.21.0-win64\\geckodriver.exe");
driver = new FirefoxDriver();
}
e_driver = new EventFiringWebDriver(driver);
eventListener = new WebEventListener();
e_driver.register(eventListener);
driver = e_driver;
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(TestUtil.PAGE_LOAD_TIMEOUT , TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(TestUtil.IMPLICIT_WAIT , TimeUnit.SECONDS);
driver.get(prop.getProperty("url"));
}
}
<!-- Method in Event Listener class which is showing in error -->
public void afterFindBy(By arg0, WebElement arg1, WebDriver arg2) {
System.out.println("Find happened on " + arg1.toString() + " Using method " + arg0.toString());
}
ERROR LOG :
[RemoteTestNG] detected TestNG version 6.11.0 Starting ChromeDriver
2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e) on port 21677 Only local connections are allowed. log4j:WARN No appenders could be
found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly. log4j:WARN See
http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Sep 09, 2018 9:10:58 AM org.openqa.selenium.remote.ProtocolHandshake
createSession INFO: Detected dialect: OSS driver=ChromeDriver: chrome
on XP (ac62d0828d89443b9bedefa67a824225) Inside the afterNavigateTo to
https://www.ss.com/en FAILED CONFIGURATION: #BeforeMethod setUp
java.lang.NullPointerException at
com.ss.qa.util.WebEventListener.afterFindBy(WebEventListener.java:31)
at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564) at
org.openqa.selenium.support.events.EventFiringWebDriver$1.invoke(EventFiringWebDriver.java:81)
at com.sun.proxy.$Proxy9.afterFindBy(Unknown Source) at
org.openqa.selenium.support.events.EventFiringWebDriver.findElement(EventFiringWebDriver.java:189)
at
org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at
org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy12.isDisplayed(Unknown Source) at
com.ss.qa.pages.HomePage.clickSearchLink(HomePage.java:67) at
com.ss.qa.testcases.SearchPageTest.setUp(SearchPageTest.java:25) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564) at
org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
at
org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:523)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:224)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:599) at
org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869) at
org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193) at
org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
at
org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:744) at
org.testng.TestRunner.run(TestRunner.java:602) at
org.testng.SuiteRunner.runTest(SuiteRunner.java:380) at
org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375) at
org.testng.SuiteRunner.privateRun(SuiteRunner.java:340) at
org.testng.SuiteRunner.run(SuiteRunner.java:289) at
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at
org.testng.TestNG.runSuitesSequentially(TestNG.java:1301) at
org.testng.TestNG.runSuitesLocally(TestNG.java:1226) at
org.testng.TestNG.runSuites(TestNG.java:1144) at
org.testng.TestNG.run(TestNG.java:1115) at
org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Kindly suggest.
WebEventListener.java:31: keep the null check, one of the elements you are using is throwing a null pointer exception.
If you can post the printed content of the WebEventListener.java on line 31, then we can better examine the problem. To do that, change this line:
public void afterFindBy(By arg0, WebElement arg1, WebDriver arg2) {
System.out.println("Find happened on " + arg1 + " Using method " + arg0);
}
As per you comment " When the control goes into homepage.clickSearchLink() method, the test ends and error comes."
check whether this method "homepage.clickSearchLink()" is returning searchpage instance.
the method should be
~public Searchpage clickSearchLink(){
//click on element to get search page
//Also check whether element is present on page or not.
return new Searchpage();
}~

Mockito + PowerMock + TestNG + Libgdx

I'm trying add the powermock library to the working project, but I'm getting errors.
How I add it:
1) AbsTest extends PowerMockTestCase
2) Build.gradle dependencies
3) In some test add #PrepareForTest({SomeClass.class}). After this step this error occured.
In build.gradle all libraries are included.
Error occured in a place where initialize HeadlessApplication for use Gdx.* static vars.
All tests in project extend this class:
abstract public class AbsTest extends PowerMockTestCase {
static {
initGdx();
}
protected static void initGdx() {
// Initialize libgdx headless for use static vars (e.g. Gdx.input.setInputProcessor)
final HeadlessApplicationConfiguration config = new HeadlessApplicationConfiguration();
config.renderInterval = 1f / 60; // Likely want 1f/60 for 60 fps
new HeadlessApplication(mock(Core.class), config); <=== ERROR LINE
}
#BeforeMethod(alwaysRun = true)
public void initMethod() throws Exception {
// Initialize mocks
MockitoAnnotations.initMocks(this);
}
}
Errors:
org.testng.TestNGException: An error occurred while instantiating
class ru.coolone.adventure_emulation.input.InputGroupsTest: null at
org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:435)
at
org.testng.internal.ClassHelper.createInstance(ClassHelper.java:336)
at
org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:125)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:190) at
org.testng.TestClass.getInstances(TestClass.java:95) at
org.testng.TestClass.initTestClassesAndInstances(TestClass.java:81)
at org.testng.TestClass.init(TestClass.java:73) at
org.testng.TestClass.(TestClass.java:38) at
org.testng.TestRunner.initMethods(TestRunner.java:389) at
org.testng.TestRunner.init(TestRunner.java:271) at
org.testng.TestRunner.init(TestRunner.java:241) at
org.testng.TestRunner.(TestRunner.java:167) at
org.testng.SuiteRunner$DefaultTestRunnerFactory.newTestRunner(SuiteRunner.java:663)
at org.testng.SuiteRunner.init(SuiteRunner.java:260) at
org.testng.SuiteRunner.(SuiteRunner.java:198) at
org.testng.TestNG.createSuiteRunner(TestNG.java:1271) at
org.testng.TestNG.createSuiteRunners(TestNG.java:1249) at
org.testng.TestNG.runSuitesLocally(TestNG.java:1107) at
org.testng.TestNG.runSuites(TestNG.java:1028) at
org.testng.TestNG.run(TestNG.java:996) at
org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72) at
org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:127)
Caused by: java.lang.ExceptionInInitializerError at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at
org.powermock.modules.testng.internal.TestClassInstanceFactory.create(TestClassInstanceFactory.java:51)
at
org.powermock.modules.testng.internal.PowerMockClassloaderObjectFactory.newInstance(PowerMockClassloaderObjectFactory.java:46)
at
org.powermock.modules.testng.PowerMockObjectFactory.newInstance(PowerMockObjectFactory.java:43)
at
org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:423)
... 21 more Caused by: java.lang.IllegalStateException: Could not
initialize plugin: interface org.mockito.plugins.MockMaker at
org.mockito.internal.configuration.plugins.PluginLoader$1.invoke(PluginLoader.java:66)
at com.sun.proxy.$Proxy19.isTypeMockable(Unknown Source) at
org.mockito.internal.util.MockUtil.typeMockabilityOf(MockUtil.java:29)
at
org.mockito.internal.util.MockCreationValidator.validateType(MockCreationValidator.java:22)
at
org.mockito.internal.creation.MockSettingsImpl.validatedSettings(MockSettingsImpl.java:186)
at
org.mockito.internal.creation.MockSettingsImpl.confirm(MockSettingsImpl.java:180)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:62) at
org.mockito.Mockito.mock(Mockito.java:1729) at
org.mockito.Mockito.mock(Mockito.java:1642) at
ru.coolone.adventure_emulation.AbsTest.initGdx(AbsTest.java:37) at
ru.coolone.adventure_emulation.AbsTest.(AbsTest.java:30) ...
29 more Caused by: java.lang.IllegalStateException: Failed to load
interface org.mockito.plugins.MockMaker implementation declared in
sun.misc.CompoundEnumeration#7dc3712 at
org.mockito.internal.configuration.plugins.PluginLoader.loadImpl(PluginLoader.java:101)
at
org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:45)
at
org.mockito.internal.configuration.plugins.PluginRegistry.(PluginRegistry.java:18)
at
org.mockito.internal.configuration.plugins.Plugins.(Plugins.java:17)
at org.mockito.internal.util.MockUtil.(MockUtil.java:24) ...
37 more Caused by: java.lang.ClassCastException: Cannot cast
org.powermock.api.mockito.mockmaker.PowerMockMaker to
org.mockito.plugins.MockMaker at
java.lang.Class.cast(Class.java:3369) at
org.mockito.internal.configuration.plugins.PluginLoader.loadImpl(PluginLoader.java:97)
... 41 more
build.gradle:
...
testCompile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
testCompile "com.badlogicgames.gdx:gdx-backend-headless:$gdxVersion"
testCompile 'org.testng:testng:6.13.1'
testCompile "org.mockito:mockito-core:2.8.9"
testCompile "org.powermock:powermock-api-mockito2:1.7.3"
testCompile "org.powermock:powermock-module-testng:1.7.3"
...
I'm fixed this. Im just move initGdx(); to overloaded beforePowerMockTestMethod() or beforePowerMockTestClass() and delete mockito annotations initialization because it execute in the parent class.
fixed AbsTest class:
abstract public class AbsTest extends PowerMockTestCase {
protected static void initGdx() {
// Initialize libgdx headless for use static vars (e.g. Gdx.input.setInputProcessor)
final HeadlessApplicationConfiguration config = new HeadlessApplicationConfiguration();
config.renderInterval = 1f / 60; // Likely want 1f/60 for 60 fps
new HeadlessApplication(mock(Core.class), config);
}
#BeforeMethod
#Override
protected void beforePowerMockTestMethod() throws Exception {
initGdx();
super.beforePowerMockTestMethod();
}
}
or with overload beforePowerMockTestClass method
abstract public class AbsTest extends PowerMockTestCase {
protected static void initGdx() {
// Initialize libgdx headless for use static vars (e.g. Gdx.input.setInputProcessor)
final HeadlessApplicationConfiguration config = new HeadlessApplicationConfiguration();
config.renderInterval = 1f / 60; // Likely want 1f/60 for 60 fps
new HeadlessApplication(mock(Core.class), config);
}
#BeforeClass
#Override
protected void beforePowerMockTestClass() throws Exception {
super.beforePowerMockTestClass();
initGdx();
}
}

Exception while runnig a javafx application jar file

I have a problem here with my javafx application jar, generated by Eclipse mars. Actually everything is running pretty well if I am running inside eclipse. However when I use the command line and try to run the jar of my application which was previously created by eclipse, using the command:
java -jar TalanTestingWithXPathFX.jar
I got a lot of errors in my terminal. The error are the following:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: Location is not set.
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at talan.test.webApp.MainApp.initRootLayout(Unknown Source)
at talan.test.webApp.MainApp.start(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162 (Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
... 1 more
Exception running application talan.test.webApp.MainApp
This is some code from the main class
public class MainApp extends Application {
#FXML
private static Stage primaryStage;
#FXML
private AnchorPane rootLayout;
public Project mainProject;
public static rootLayOutController rootController;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setResizable(true);
this.primaryStage.setTitle("AutoGenDriver");
initRootLayout();
//showSubWindow();
}
/**
* Initializes the root layout.
*/
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("./view/rootLayOut.fxml"));
rootLayout = loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
//
primaryStage.setScene(scene);
rootController=loader.getController();
// Give the controller access to the main app.
rootLayOutController controller = loader.getController();
controller.setMainApp(this);
primaryStage.show();
} catch (IOException e) {
System.out.println("Loading error");
}
}
public void setProject(Project p){
this.mainProject = p;
}
/**
* Called when the user clicks New Project.
*/
#FXML
public static Project showNewProjectDialog() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/newProjectDialog.fxml"));
AnchorPane page = loader.load();
// Create the dialog Stage.
Stage dialogStage = new Stage();
dialogStage.setTitle("Add new Test Project");
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.initOwner(primaryStage);
Scene scene = new Scene(page);
dialogStage.setScene(scene);
// Set the project into the controller.
newProjectDialogController controller = loader.getController();
controller.setDialogStage(dialogStage);
// controller.setProject(project);
// Show the dialog and wait until the user closes it
dialogStage.showAndWait();
return controller.getProject();
} catch (IOException e) {
System.out.println("Loading error");
return null;
}
}
public static void setPrimaryStage(Stage primaryStage) {
MainApp.primaryStage = primaryStage;
}
/**
* Returns the main stage.
* #return
*/
public static Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
this is some code from the rootLayOutController class
public void setRootTreeView(String nameProject) {
Image image=new Image(new File("C:\\Users\\DELL 3521\\workspaceMars\\TalanTestingFX\\Images\\dossier.png").toURI().toString(),20,20,true,true);
ImageView imv= new ImageView();
imv.setImage(image);
TreeItem<String> rootNode = new TreeItem<String>(tempProject.getName(),imv);
rootNode.setExpanded(true);
testProject.add(rootNode);
t.setRoot(rootNode);
}
/**
* add sub Elements to the TreeView
*
* #param mainApp
*/
public void addItemToTreeView(String item) {
testProject.get(0).getChildren().add(new TreeItem<String>(item));
}
public static Template getTemplate() {
return template;
}
public static void setTemplate(Template template) {
rootLayOutController.template = template;
}
public AnchorPane getContent() {
return content;
}
public void setContent(AnchorPane content) {
this.content = content;
}
/**
* Initializes the controller class. This method is automatically called
* after the fxml file has been loaded.
*/
#FXML
private void initialize() {
handleTreeViewSelectElement();
newSuiteItem.setDisable(true);
openPageItem.setDisable(true);
cnxItem.setDisable(true);
openPageItem.setDisable(true);
scItem.setDisable(true);
acItem.setDisable(true);
dactItem.setDisable(true);
}

RestAssuredMockMvc - Autowire repositories are null

I'm testing a rest controller using RestAssuredMockMvc. This is my code
/*Repository*/
package com.rest.api.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.stereotype.Repository;
import com.mysema.query.types.Predicate;
#Repository
public interface ClientRepository extends JpaRepository<Client, Long>,
QueryDslPredicateExecutor<Client> {
Client findByClientId(Integer clientId);
Client findOne(Predicate predicate);
List<Client> findAll(Predicate predicate);
}
/*Services to be offered*/
package com.rest.api.service;
import java.util.List;
import com.mysema.query.types.Predicate;
import com.rest.api.model.Client;
import com.rest.api.repository.ClientRepository;
public interface ClientService {
Boolean saveEnterprise(Client client, ClientRepository clientRepository);
}
/*Implementation*/
package com.rest.api.service.implementations;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
import com.mysema.query.types.Predicate;
import com.rest.api.logging.LoggingManager;
import com.rest.api.model.Client;
import com.rest.api.repository.ClientRepository;
import com.rest.api.service.ClientService;
#Service
public class ClientImpl implements ClientService {
#Override
public Boolean saveEnterprise(Client client,
ClientRepository clientRepository) {
try {
LoggingManager.info(getClass(), "CLIENT="+client);
if(clientRepository == null){
LoggingManager.info(getClass(), "CLIENT REPO NULL");
}
if (client != null) {
clientRepository.save(client);
}
} catch (Exception e) {
LoggingManager.debug(getClass(),
"Error while saving assistance details");
e.printStackTrace();
return false;
}
return true;
}
}
/* CONTROLLER*/
#Controller
public class ClientController {
#Autowired
ClientRepository clientRepository;
#Inject
public void setRepository(ClientRepository clientRepository) {
this.clientRepository = clientRepository;
}
// Get Service Handle - A Singleton
private ClientService enterpriseServicehandle = EnterpriseClient
.getInstance().getEnterpriseService();
#RequestMapping(value = ApiEndpointConstants.CREATE_NEW_CLIENT, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, headers = "content-type=application/x-www-form-urlencoded")
#ResponseBody
public EnterpriseResponse saveEnterprise(#RequestBody Client client) {
EnterpriseResponse enterpriseResponse = new EnterpriseResponse();
enterpriseServicehandle.saveEnterprise(client, clientRepository);
enterpriseResponse.setEnterprise(client);
enterpriseResponse
.setResponseCode(212);
enterpriseResponse
.setResponseMessage("Client creation Successful");
return enterpriseResponse;
}
}
/* Test Class*/
import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.module.mockmvc.response.MockMvcResponse;
import com.rest.api.model.util.ResponseCodeConstants;
import com.rest.api.repository.AccesscodeRepository;
import com.rest.api.repository.ClientRepository;
public class ClientControllerTest {
#Autowired
private ClientRepository clientRepository;
#Autowired
private WebApplicationContext webApplicationContext;
#Autowired
private AccesscodeRepository accesscodeRepository;
#Before
public void setUp() throws Exception {
}
#After
public void tearDown() throws Exception {
}
#Test
public final void testFunctionality() {
String clientJson = "{\"name\":\"Client1\",\"clientId\":1000,\"fromEmailAddress\":\"goutham#atreya.in\"}";
MockMvcResponse clientCreationResponse = given()
.standaloneSetup(new ClientController())
.body(clientJson)
.contentType(ContentType.JSON)
.when()
.post("api/client/save")
.then()
.statusCode(200)
.extract().response();
System.out.println(clientCreationResponse.asString());
Integer clientResponseCode = clientCreationResponse.path("responseCode");
String clientResponseMessage = clientCreationResponse.path("responseMessage");
System.out.println("INT:" + clientResponseCode);
Assert.assertEquals(clientResponseCode, 211);
Assert.assertEquals(clientResponseMessage,"Client Creation Successful");
}
}
When I run the test case, I get this error (Note that, The clientRepository is NULL and throws a NPE, but the last line suggests that the client was successfully created.,
Oct 26, 2014 8:50:16 PM com.rest.api.logging.LoggingManager log
INFO: CLIENT={"clientId":1000,"name":"Client1","fromEmailAddress":"goutham#atreya.in","insertionTime":"Oct 26, 2014 8:50:16 PM"}
Oct 26, 2014 8:50:16 PM com.rest.api.logging.LoggingManager log
INFO: CLIENT REPO NULL
java.lang.NullPointerException
at com.rest.api.service.implementations.ClientImpl.saveEnterprise(ClientImpl.java:46)
at com.rest.api.controller.ClientController.saveEnterprise(ClientController.java:99)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:688)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:170)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:137)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:145)
at com.jayway.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.performRequest(MockMvcRequestSenderImpl.java:127)
at com.jayway.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.sendRequest(MockMvcRequestSenderImpl.java:327)
at com.jayway.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.post(MockMvcRequestSenderImpl.java:407)
at com.jayway.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.post(MockMvcRequestSenderImpl.java:51)
at com.rest.api.controller.ClientControllerTest.testFunctionality(ClientControllerTest.java:107)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
{"responseMessage":"Client creation Successful","responseCode":212,"enterprise":{"id":null,"clientId":1000,"name":"-Client1","fromEmailAddress":"trace-support#.net","insertionTime":1414336816443}}
INT:212
Can Anyone please guide me? What am I doing wrong? Why is my repository being null?
The endpoint does work, when Ii use Curl command and test, however, I'm unable to write a junit for unit testing, Please help
I meet exactly same problem.
When I run the project, it works fine.
But when I test controller some autowired variable becomes null, which failed the test.
In my code, I have a userWebController which does "signup" job. There is another class CustomedUserDetailsService which work with a JdbcTemplate object to add a new user to database. the JdbcTemplate object is autowired with a bean. When I test the controller, this JdbcTemplate object is null which means it is not injected successful.
I tried this following method(the jdbc bean is defined in class OnlineDBConfig), but does not work:
#ContextConfiguration( classes = {OnlineDBConfig.class})
I solve my problem with following solution:
1, move the failed_autowired object to the Test class (StandaloneUserControllerTest) directly.
2, pass the object to the controller class which use it.
Following is the final test class:
public class StandaloneUserControllerTest extends AbstractSpringJunit4Tests {
#Autowired
#Qualifier("jdbcOnline")
protected JdbcTemplate jdbc;
#Before
public void before(){
RestAssuredMockMvc.standaloneSetup(new UserWebController(jdbc) ) ;
if( jdbc == null )
fail("autowired failed again") ;
}
}
It is terrible, but it works.
Hope there will be better solution.