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

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();
}~

Related

I get problem when I run Junit on my test, browser is not opening

I am new in Selenium and I have problem with Junit.
Problem is browser is not starting when I use Junit annotations, if I write the same test case without Junit, it runs with no problem. I have also tried with TestNG and I get the same problem
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Smoke {
public WebDriver driver = new ChromeDriver();
#Before
public void testSetUp() {
System.setProperty("webdriver.chrome.driver", "./Driver/chromedriver.exe");
driver.get("url");
driver.findElement(By.xpath("/html/body/p/a")).click();
}
#Test
public void aboutPage() {
driver.findElement(By.xpath("//*[#id=\"menu-item-137\"]/a")).click();
}
#Test
public void productsPage() {
driver.findElement(By.xpath("//*[#id=\"menu-item-17\"]/a")).click();
}
#After
public void testTearDown()
{
driver.quit();
}
}
I get this in console:
java.lang.IllegalStateException: The path to the driver executable The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from https://chromedriver.storage.googleapis.com/index.html
at org.openqa.selenium.internal.Require$StateChecker.nonNull(Require.java:280)
at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:132)
at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:38)
at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:231)
at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:434)
at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:127)
at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:46)
at tests.Smoke.(Smoke.java:13)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:250)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:260)
at org.junit.runners.BlockJUnit4ClassRunner$2.runReflectiveCall(BlockJUnit4ClassRunner.java:309)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:93)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

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

Building a web application with embedded-jetty and jersey .. with request dispatching

I am setting a web application with embedded jetty and jersey .As i am fairly new with concepts, it is difficult to load a sample webpage index.html. When i target it as localhost:8989/myServlet i see the code flow through my servlet . But request dispatcher always returns null.
Please let me know with this:
Main class:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class MainApp {
public static void main(String[] args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(8989);
jettyServer.setHandler(context);
ServletHandler handler =new ServletHandler();
handler.addServletWithMapping(MyServletHandler.class,"/myServlet");
jettyServer.setHandler(handler);
ServletHolder jerseyServlet = context.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter(
"jersey.config.server.provider.classnames",
Entry.class.getCanonicalName());
try {
jettyServer.start();
jettyServer.join();
} finally {
jettyServer.destroy();
}
}
}
Myservlet class:
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyServletHandler extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Control is in servlet");
RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.html"); // this returns null. hence i am unable to request dispatch to view the html webpage.
}
}
I use Maven to build the application and i have placed index.html in src/main/resources directory
This works, but you'll have to properly setup the ServletContext so that the request.getRequestDispatcher() can do something.
For starters, your ServletContextHandler MUST have a Resource Base setup.
You'll have to setup a DefaultServlet so that the request dispatcher can be returned properly.
You'll also have to use embedded-jetty properly, don't use ServletHandler directly like that. Use the ServletHolder if you must, but otherwise just use the ServletContextHandler directly.
Here's an example of this behavior.
Run with a System Property of baseResource pointing to a directory where you have a index.html.
package jetty.dispatching;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.resource.Resource;
import static java.nio.charset.StandardCharsets.UTF_8;
public class DispatchingToDefaultServletDemo
{
public static void main(String[] args) throws Exception
{
DispatchingToDefaultServletDemo demo = new DispatchingToDefaultServletDemo();
try
{
demo.startServer();
demo.makeRequests();
}
finally
{
demo.stopServer();
}
}
private Server server;
public void startServer() throws Exception
{
server = new Server(8989);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
// Must have Resource Base for proper ServletContext (even if it points to an empty URI directory in a JAR file)
context.setBaseResource(getBaseResource());
// Don't use ServletHandler directly!
context.addServlet(MyServletHandler.class, "/myServlet");
// Add DefaultServlet last on ServletContextHandler to be able to serve content from resource base.
// It must be named "default" (per servlet spec)
ServletHolder defaultHolder = new ServletHolder("default", DefaultServlet.class);
defaultHolder.setInitParameter("dirAllowed", "true");
context.addServlet(defaultHolder, "/"); // this is the default url-pattern
HandlerList handlers = new HandlerList();
handlers.addHandler(context);
handlers.addHandler(new DefaultHandler()); // always last in handler tree
server.setHandler(handlers);
server.start();
}
public Resource getBaseResource() throws IOException
{
String baseResourceLocation = System.getProperty("baseResource");
if (baseResourceLocation == null)
{
baseResourceLocation = System.getProperty("user.dir");
}
Resource resource = Resource.newResource(baseResourceLocation);
System.out.println("Base Resource is " + resource);
return resource;
}
private void stopServer() throws Exception
{
server.stop(); // use .stop() NOT .destroy()
}
private void makeRequests()
{
performGET("/myServlet");
performGET("/");
}
private void performGET(String requestPath)
{
try
{
URI uri = server.getURI().resolve(requestPath);
System.out.println("Requesting GET on " + uri);
HttpURLConnection http = (HttpURLConnection) uri.toURL().openConnection();
System.out.println(" Response Status code = " + http.getResponseCode());
try (InputStream in = http.getInputStream())
{
System.out.println(" Response Body: " + IO.toString(in, UTF_8));
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static class MyServletHandler extends HttpServlet
{
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/index.html");
System.out.println("request Dispatcher = " + requestDispatcher);
requestDispatcher.forward(request, response);
}
}
}
The output ...
$ java -DbaseResource=/home/joakim/code/jetty/bases/listing-base/rez/welcomish/ -classpath <..snip..> jetty.dispatching.DispatchingToDefaultServletDemo
2019-04-18 15:15:15.595:INFO::main: Logging initialized #180ms to org.eclipse.jetty.util.log.StdErrLog
Base Resource is file:///home/joakim/code/jetty/bases/listing-base/rez/welcomish/
2019-04-18 15:15:15.678:INFO:oejs.Server:main: jetty-9.4.15.v20190215; built: 2019-02-15T16:53:49.381Z; git: eb70b240169fcf1abbd86af36482d1c49826fa0b; jvm 1.8.0_192-b12
2019-04-18 15:15:15.725:INFO:oejs.session:main: DefaultSessionIdManager workerName=node0
2019-04-18 15:15:15.726:INFO:oejs.session:main: No SessionScavenger set, using defaults
2019-04-18 15:15:15.727:INFO:oejs.session:main: node0 Scavenging every 660000ms
2019-04-18 15:15:15.736:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler#482f8f11{/,file:///home/joakim/code/jetty/bases/listing-base/rez/welcomish/,AVAILABLE}
2019-04-18 15:15:15.747:INFO:oejs.AbstractConnector:main: Started ServerConnector#3ffc5af1{HTTP/1.1,[http/1.1]}{0.0.0.0:8989}
2019-04-18 15:15:15.747:INFO:oejs.Server:main: Started #333ms
Requesting GET on http://127.0.1.1:8989/myServlet
request Dispatcher = Dispatcher#0x5d8c6ff2{null,/index.html}
Response Status code = 200
Response Body: <h1>My welcomish HTML</h1>
Requesting GET on http://127.0.1.1:8989/
Response Status code = 200
Response Body: <h1>My welcomish HTML</h1>
2019-04-18 15:15:15.827:INFO:oejs.AbstractConnector:main: Stopped ServerConnector#3ffc5af1{HTTP/1.1,[http/1.1]}{0.0.0.0:8989}
2019-04-18 15:15:15.827:INFO:oejs.session:main: node0 Stopped scavenging
2019-04-18 15:15:15.829:INFO:oejsh.ContextHandler:main: Stopped o.e.j.s.ServletContextHandler#482f8f11{/,file:///home/joakim/code/jetty/bases/listing-base/rez/welcomish/,UNAVAILABLE}
Process finished with exit code 0

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.

Powermock ProcessBuilder constructor with String[].class argument

When I tried to powermock the ProcessBuilder constructor, it successes if the argument is an ArrayList, but it fails when the argument is a String array.
The class to be tested is:
package test;
import java.util.ArrayList;
public class MockProcessBuilder {
public void instance1() throws Exception {
String chmodCmd[] = { "/bin/chmod", "755", "/path/to/dest" + "/" + "file.txt" };
// constructor with String[].class
ProcessBuilder pb = new ProcessBuilder(chmodCmd);
pb.redirectErrorStream(true);
Process proc = pb.start();
proc.waitFor();
}
public void instance2() throws Exception {
ArrayList<String> cmdArrayList = new ArrayList<String>();
cmdArrayList.add("/bin/execScript");
cmdArrayList.add("exec");
cmdArrayList.add("ls -altr");
// constructor with ArrayList.class
ProcessBuilder pb = new ProcessBuilder(cmdArrayList);
pb.redirectErrorStream(true);
Process proc = pb.start();
proc.waitFor();
}
}
The test class is:
package test;
import static org.mockito.Matchers.isA;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.ArrayList;
import java.util.List;
#RunWith(PowerMockRunner.class)
#PrepareForTest({MockProcessBuilder.class, ProcessBuilder.class})
public class MockProcessBuilderTest {
#Mock ProcessBuilder pb;
#Mock Process proc;
// fail. NullPointerException
#Test
public void testInstance1() throws Exception {
PowerMockito.whenNew(ProcessBuilder.class).withParameterTypes(String[].class).withArguments(isA(String[].class)).thenReturn(pb);
Mockito.when(pb.start()).thenReturn(proc);
MockProcessBuilder mpb = new MockProcessBuilder();
mpb.instance1();
}
// success
#Test
public void testInstance2() throws Exception {
PowerMockito.whenNew(ProcessBuilder.class).withParameterTypes(List.class).withArguments(isA(ArrayList.class)).thenReturn(pb);
Mockito.when(pb.start()).thenReturn(proc);
MockProcessBuilder mpb = new MockProcessBuilder();
mpb.instance2();
}
}
The first test case fails with error:
java.lang.NullPointerException
Could anyone know how to mock the first constructor?
Thanks
EDIT
full trace:
java.lang.NullPointerException
at test.MockProcessBuilder.instance1(MockProcessBuilder.java:14)
at test.MockProcessBuilderTest.testInstance1(MockProcessBuilderTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:88)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:101)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
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:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
The testInstance1() test is failing because the argument matcher isA(String[].class) doesn't match the String varargs arguments that you're giving. To make the test pass, replace the testInstance1() line
PowerMockito.whenNew(ProcessBuilder.class).withParameterTypes(String[].class).
withArguments(isA(String[].class)).thenReturn(pb);
with
PowerMockito.whenNew(ProcessBuilder.class).withParameterTypes(String[].class).
withArguments(anyVararg()).thenReturn(pb);
Powermock is intercepting the call to the ProcessBuilder varargs constructor due to PowerMockito.whenNew(ProcessBuilder.class).withParameterTypes(String[].class) matching the varargs constructor. However, because withArguments(isA(String[].class)) does not match, the thenReturn gets ignored and Powermock just returns null instead of the pb mock.
See also How to properly match varargs in Mockito