RestAssuredMockMvc - Autowire repositories are null - junit

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.

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)

AEM Mockito unit testing issue

Since i am new to Mockito and AEM model java. I have a gone through some docs and wrote my first Mockito file for AEM Model java. In my code i've not see any errors, but while running i am not getting success and can't complete the code coverage 100%. Can anyone correct/help me to fix my code[given sample java with respective mockito file]
Java File:
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.abc.cc.ddd.ResourceResolverService;
import com.abc.cc.ddd.services.models.bean.Accordion;
#Model(adaptables = SlingHttpServletRequest.class)
public class AccordionModel {
private final static Logger log = LoggerFactory.getLogger(AccordionModel.class);
#SlingObject
private SlingHttpServletRequest request;
#Inject
public ResourceResolverService resolverService;
private Resource resource;
public List < Accordion > accordionList = new ArrayList < Accordion > ();
#PostConstruct
protected void init() throws LoginException, JSONException {
log.info("AccordionModel init method Start");
resource = request.getResource();
final ValueMap configurationOptionProperties = resource.getValueMap();
log.debug("iconfigurationOptionProperties is " + configurationOptionProperties);
String count = configurationOptionProperties.get("count", String.class);
if (count != null) {
for (int i = 1; i <= Integer.valueOf(count); i++) {
Accordion accordion = new Accordion();
String title = configurationOptionProperties.get("title" + i, String.class);
String rte = configurationOptionProperties.get("rte" + i, String.class);
accordion.setTitle(title);
accordion.setRte(rte);
accordionList.add(accordion);
}
}
log.info("AccordionModel init method End");
}
public List < Accordion > getAccordionList() {
return accordionList;
}
}
Mockito code
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import com.abc.cc.ddd.ResourceResolverService;
import com.abc.cc.ddd.services.models.bean.Accordion;
#RunWith(MockitoJUnitRunner.class)
public class AccordionModelTest {
#InjectMocks
private AccordionModel accordionModel;
#Mock
Resource resource;
#Mock
SlingHttpServletRequest request;
#Mock
ResourceResolverService resourceResolverService;
#Mock
ValueMap valuemap;
public List < Accordion > accordionList = new ArrayList < Accordion > ();
String count = "6";
//max count, based on this count loop execute and get/set into the list
#Before
public void setUp() throws Exception {
when(request.getResource()).thenReturn(resource);
when(resource.getValueMap()).thenReturn(valuemap);
}
#Test
public void shouldReturnNullWhenPropertyIsNull() throws LoginException, JSONException {
when(valuemap.get("count", String.class)).thenReturn(null);
accordionModel.init();
assertEquals(accordionModel.getAccordionList(), null);
}
#Test
public void shouldReturnWhenPropertyNotNull() throws LoginException, JSONException {
when(valuemap.get("count", String.class)).thenReturn("count");
accordionModel.init();
assertEquals(accordionModel.getAccordionList(), count);
}
}
Errors in program its showing line--> accordionModel.init();
java.lang.NumberFormatException: For input string: "count"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
at com..services.sling.models.AccordionModel.init(AccordionModel.java:44) at
com..services.sling.models.AccordionModelTest.
shouldReturnWhenPropertyNotNull(AccordionModelTest.java:55)
java.lang.AssertionError: expected:<[]> but was:<null>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:834)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
at com..services.sling.models.AccordionModelTest.
shouldReturnNullWhenPropertyIsNull(AccordionModelTest.java:53)
java.lang.AssertionError: expected:<[]> but was:<null>
If you return null your list is empty. So adjust your test.
Consider renaming the method name as well.
If thats not what you want, you'll need to change your implementation.
#Test
public void shouldReturnNullWhenPropertyIsNull() throws LoginException, JSONException {
when(valuemap.get("count", String.class)).thenReturn(null);
accordionModel.init();
assertTrue(accordionModel.getAccordionList().isEmpty());
}
java.lang.NumberFormatException: For input string: "count"
"count" can not be converted into an Integer. Try using your count variable ("6") instead.
You should check the content of the list, for now I adjusted it to check that the list has the correct size.
#Test
public void shouldReturnWhenPropertyNotNull() throws LoginException, JSONException {
when(valuemap.get("count", String.class)).thenReturn(count);
accordionModel.init();
assertEquals(Integer.valueOf(count), accordionModel.getAccordionList().size());
}
Note that generally the parameter order for assert's should be expected vs actual.

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

404 NullPointerException with AngularJs Java and Jersey

I've been asked to make an App with AngularJs, Bootstrap, Java and Tomcat as a server. I'm new with java ee so maybe my error is quite simple, but I can't find a solution.
So when I start the project I see my angular app, but when i press a button and it calls http://localhost:8080/MissingDogPoc/res/dog I get this error:
Http Status 500:
java.lang.NullPointerException
com.gabriel.missingdogpoc.service.AbstractFacade.findAll(AbstractFacade.java:42)
com.gabriel.missingdogpoc.service.DogFacadeREST.findAll(DogFacadeREST.java:69)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1511)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1442)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381)
com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
SOLUTION
First if you have a web.xml in your WEB-INF you don't need it as long as you have an "ApplicatiationConfig.java" (This is auto-generated if you follow the netbeans tutorials that are out there)
The code will be like this:
package com.gabriel.missingdogpoc.service;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("api")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(com.gabriel.missingdogpoc.service.DogFacadeREST.class);
}
}
Then since Tomcat its a "Web-Server" and not an "Application Server" we need to manage the entities ourselves! So we have to make our Entity manager:
LocalEntityManagerFactory.java
package com.gabriel.missingdogpoc.util;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
#WebListener
public class LocalEntityManagerFactory implements ServletContextListener{
private static EntityManagerFactory emf;
#Override
public void contextInitialized(ServletContextEvent event) {
emf = Persistence.createEntityManagerFactory("com.gabriel_MissingDogPoc_war_1.0-SNAPSHOTPU");
}
#Override
public void contextDestroyed(ServletContextEvent event) {
emf.close();
}
public static EntityManager createEntityManager() {
if (emf == null) {
throw new IllegalStateException("Context is not initialized yet.");
}
return emf.createEntityManager();
}
}
And now since we have our own entity manager we need to use it in our rest service. You will probably have "Abrstract Facade" if you generated it with netbeans, and you will have to replace:
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().getTransaction().begin();
getEntityManager().persist(entity);
getEntityManager().getTransaction().commit();
}
public List<T> findAll() {
getEntityManager().getTransaction().begin();
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
List<T> res= getEntityManager().createQuery(cq).getResultList();
getEntityManager().getTransaction().commit();
return res;
}
If you have any problems with the backend you can check my code in github /Gaabooo/MissingDogPoc/
Your problem is that you're using Tomcat, which is an implementation of the Servlet and JSP specifications.
You've tried to turn it into a JavaEE 7 web container by adding Jersey and EclipseLink to it. Unfortunately it will still be missing the integration between the components. In your case, Jersey has no idea that it needs to inject an EntityManager into your DogFacadeREST object, so you get a NullPointerException as soon as you try to call it. Additionally, the #Stateless annotation will be completely ignored because you need to include EJB support as well for this.
It's way easier to use something like WildFly, TomEE or GlassFish and then you can throw away all those dependencies (except for the javaee-web-api).

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