Nullpoint exception message Selenium springboot - java

I am currently developing a selenium springboot framework using jUnit. This is my first time using springboot and I keep getting nullpoint exception error. Can someone please help me with this:
Error message
Start driver
Quiting driver
java.lang.NullPointerException
at com.spring.selenium.base.base.setUp(base.java:44)
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:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.RunBefores.invokeMethod(RunBefores.java:33)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.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.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
java.lang.NullPointerException
at com.spring.selenium.base.base.tearDown(base.java:51)
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:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.RunAfters.invokeMethod(RunAfters.java:46)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:33)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.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.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Process finished with exit code -1
Base Page
package com.spring.selenium.base;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public abstract class base {
public WebDriver driver;
protected Properties prop;
public base() {
try {
prop = new Properties();
FileInputStream ip = new FileInputStream(System.getProperty("user.dir") + "/src/main/resources/config.properties");
prop.load(ip);
} catch (
FileNotFoundException e) {
e.printStackTrace();
} catch (
IOException e) {
e.printStackTrace();
}
}
#PostConstruct
private void init(WebDriver driver){
PageFactory.initElements(driver, this);
System.out.println("Postconstruct lunched");
}
#Before
public void setUp() {
System.out.println("Start driver");
driver.get(prop.getProperty("url"));
}
#After
public void tearDown() {
System.out.println("Quiting driver");
driver.quit();
}
}
WebDriver page
package com.spring.selenium.config;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class webDriver {
#Bean
public WebDriver chromeDriver(){
WebDriverManager.chromedriver().setup();
return new ChromeDriver();
}
#Bean
public WebDriver firefoxDriver(){
WebDriverManager.firefoxdriver().setup();
return new FirefoxDriver();
}
#Bean
public WebDriver edgeDriver(){
WebDriverManager.edgedriver().setup();
return new EdgeDriver();
}
}
Home Page
package com.spring.selenium.objectRepository;
import com.spring.selenium.base.base;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.stereotype.Component;
import org.testng.Assert;
import java.time.Duration;
#Component
public class homePage extends base {
private boolean SuccessResult;
WebDriverWait wait;
#FindBy(xpath = "//*[#id=\"left\"]/div[1]/div/button/span/span/span")
private WebElement menuLabel;
public void WaitUntilHomePageText() {
SuccessResult = false;
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
for (int i = 1; i <= 3; i++) {
try {
wait.until(ExpectedConditions.visibilityOf(menuLabel));
System.out.println("Waiting until the Home page is displayed");
SuccessResult = true;
break;
} catch (Exception ex) {
}
}
if (!SuccessResult) {
Assert.fail("Home page is not displayed");
}
}
public void clickOnMenuButton() {
menuLabel.click();
}
}
TestCase
package com.spring.selenium.testcases;
import com.spring.selenium.base.base;
import com.spring.selenium.objectRepository.homePage;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
#SpringBootTest
public class regressiontests extends base {
#Autowired
protected homePage homePage;
#Test
public void navigateToPayeePage() throws InterruptedException {
homePage.WaitUntilHomePageText();
homePage.clickOnMenuButton();
}
}

Related

Using mockito-inline MockedConstruction to mock FileInputStream throws Could not initialize mocked construction

I'm trying to get rid of PowerMock and replace it with mockito-inline new feature Mocking object construction ,
as I can't refactor the old source code.
One of the test classes I have is mocking FileInputStream,
the class under test FileViewer
import java.awt.Button;
import java.awt.Event;
import java.awt.Font;
import java.awt.TextArea;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileViewer extends java.awt.Frame {
private static final long serialVersionUID = 1L;
Button close;
GUIListener fGuiListener;
public FileViewer() {
super();
fGuiListener = new GUIListener();
addWindowListener(fGuiListener);
}
public FileViewer(String filename) throws IOException {
super("FileViewer: " + filename);
fGuiListener = new GUIListener();
addWindowListener(fGuiListener);
File f = new File(filename);
int size = (int) f.length();
int bytes_read = 0;
byte[] data = new byte[size];
try (FileInputStream in = new FileInputStream(f)) {
while (bytes_read < size)
bytes_read += in.read(data, bytes_read, size - bytes_read);
}
TextArea ta = new TextArea(new String(data, 0), 24, 80);
ta.setFont(new Font("Helvetica", Font.PLAIN, 12));
ta.setEditable(false);
this.add("Center", ta);
close = new Button("Close");
this.add("South", close);
this.pack();
this.show();
}
public boolean action(Event e, Object what) {
if (e.target == close) {
this.hide();
this.dispose();
return true;
} else
return false;
}
}
and the original unit test using powermock was
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.FileInputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#PowerMockIgnore({ "javax.management.*", "javax.security.*" })
#RunWith(PowerMockRunner.class)
#PrepareForTest({ FileViewer.class, FileInputStream.class, java.awt.Frame.class })
public class FileViewerTest {
String dir = System.getProperty("user.dir");
String fileName = "/testFiles/testRead.txt";
FileInputStream mockStream = null;
#Before
public void setup() throws Exception {
mockStream = Mockito.mock(FileInputStream.class);
when(mockStream.read(any(byte[].class), anyInt(), anyInt())).thenReturn(2000);
PowerMockito.whenNew(FileInputStream.class).withAnyArguments().thenReturn(mockStream);
}
#Test
public void testFileViewer_wFilename() throws Exception {
FileViewer spy = Mockito.spy(new FileViewer(dir + fileName));
verify(mockStream, times(1)).close();
spy.dispose();
}
}
I tried to follow the example Mock Java Constructors With Mockito | Configuration and Examples
and creat a new unit test using MockedConstruction as the following
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.FileInputStream;
import org.junit.Test;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
public class FileViewerMockitoTest {
String dir = System.getProperty("user.dir");
String fileName = "/testFiles/testRead.txt";
#Test
public void testFileViewerWithFilename() throws Exception {
try (MockedConstruction<FileInputStream> mocked = Mockito.mockConstruction(FileInputStream.class,
(mock, context) -> {
// further stubbings ...
when(mock.read(any(), any(), any())).thenReturn((int) new File(dir + fileName).length() + 1);
})) {
FileViewer cut = new FileViewer(dir + fileName);
verify(mocked, times(1)).close();
cut.dispose();
}
}
}
But I got the following Exception
org.mockito.exceptions.base.MockitoException: Could not initialize mocked construction
at java.io.FileInputStream.<init>(FileInputStream.java)
at sun.misc.URLClassPath$FileLoader$1.getInputStream(URLClassPath.java:1385)
at sun.misc.Resource.cachedInputStream(Resource.java:77)
at sun.misc.Resource.getByteBuffer(Resource.java:160)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:455)
at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at com.cds.nrd.xss.util.FileViewerMockitoTest.testFileViewerWithFilename(FileViewerMockitoTest.java:30)
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:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:43)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:82)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:73)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
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)
Caused by: java.lang.NullPointerException
at com.cds.nrd.xss.util.FileViewerMockitoTest.lambda$0(FileViewerMockitoTest.java:27)
at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker$InlineConstructionMockControl.lambda$enable$0(InlineByteBuddyMockMaker.java:710)
at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.lambda$new$3(InlineByteBuddyMockMaker.java:272)
at org.mockito.internal.creation.bytebuddy.MockMethodAdvice.handleConstruction(MockMethodAdvice.java:176)
at org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher.handleConstruction(MockMethodDispatcher.java:53)
... 57 more
Any idea about the reason of the exception or how to make it work, or any alternate approach?
Found the solution:
We can't set any() parameter in the stub of the lambda function in try-with-resource
(in your case, when(mock.read(any(), any(), any())) in FileViewerMockitoTest), which will cause mock.read(any(), any(), any()) to throw an NPE: "could not unbox null" (don't know what it means).
Just simply replace (all of) these arguments to something like any(ArgClass.class), will solve the NPE problem, so do with the Could not initialize mocked construction MockitoException problem.
(How did I find the problem? By extracting the lambda function as a method, we can get the real description of the NPE in the debug environment.)
(I was surprised that there was no information on the internet other than this question.)

How to get rid of NullPointerException in Mockito unit test

I want to unit test rentBook method that is rensposible for renting.
Here is the #Service
package bookrental.service.book.rentals;
import bookrental.model.account.User;
import bookrental.model.book.Book;
import bookrental.model.book.BookRentals;
import bookrental.repository.account.UserRepository;
import bookrental.repository.book.BookRepository;
import bookrental.repository.book.BookRentalsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
#Service
public class BookRentalService {
private final UserRepository userRepository;
private final BookRepository bookRepository;
private final BookRentalsRepository bookRentalsRepository;
#Autowired
public BookRentalService(BookRepository bookRepository, BookRentalsRepository bookRentalsRepository, UserRepository userRepository) {
this.bookRepository = bookRepository;
this.bookRentalsRepository = bookRentalsRepository;
this.userRepository = userRepository;
}
public String rentBook(int userID, int bookID) {
if (userRepository.doesAccountExistsWithGivenID(userID)) {
if (bookRepository.doesBookExistsWithGivenID(bookID)) {
Book bookToRent = bookRepository.findOne(bookID);
if (bookToRent.isAvailable()) {
updateBookAvailabilityAndSaveToDb(bookToRent);
BookRentals preparedBookToRent = prepareBookToRent(userID, bookID);
bookRentalsRepository.save(preparedBookToRent);
} else {
throw new IllegalArgumentException("Book is not available");
}
} else {
throw new IllegalArgumentException("Book does not exist!");
}
} else {
throw new IllegalArgumentException("Account does not exist!");
}
return "Book was rented";
}
private BookRentals prepareBookToRent(int userID, int bookID) {
return new BookRentals(new Book(bookID), new User(userID));
}
private void updateBookAvailabilityAndSaveToDb(Book bookToRent) {
bookToRent.setAvailable(false);
bookRepository.save(bookToRent);
}
public List<BookRentals> findAllRentals() {
List<BookRentals> rentedBooks = new ArrayList<>();
bookRentalsRepository.findAll().forEach(rentedBooks::add);
return rentedBooks;
}
}
I tried to unit test it, but getting NPE. I do not know what I am doing wrong.
package bookrental.service.book.rentals;
import bookrental.model.account.User;
import bookrental.model.book.Book;
import bookrental.model.book.BookRentals;
import bookrental.repository.book.BookRentalsRepository;
import bookrental.repository.book.BookRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
#RunWith(MockitoJUnitRunner.class)
public class BookRentalServiceTest {
#Mock
BookRentalsRepository bookRentalsRepository;
#Mock
BookRepository bookRepository;
#InjectMocks
BookRentalService bookRentalService;
#Test
public void rentBook() {
Book book = createDummyBook();
User user = createDummyUser();
BookRentals bookToRent = createDummyRentedBook(user, book);
when(bookRentalsRepository.save(bookToRent)).thenReturn(bookToRent);
bookRentalService.rentBook(user.getId(), book.getId());
verify(bookRentalsRepository).save(bookToRent);
verify(bookRentalService, times(1)).rentBook(user.getId(), book.getId());
}
#Test
public void findAllRentals() {
}
private Book createDummyBook() {
return new Book(0, "W pustyni i w puszczy", "Henryk Sienkiewicz", "dramat", true);
}
private BookRentals createDummyRentedBook(User user, Book book) {
return new BookRentals(book, user);
}
private User createDummyUser() {
return new User(0, "must", "123");
}
}
Stacktrace:
java.lang.NullPointerException
at bookrental.service.book.rentals.BookRentalService.rentBook(BookRentalService.java:30)
at bookrental.service.book.rentals.BookRentalServiceTest.rentBook(BookRentalServiceTest.java:38)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
///
EDIT
#Test
public void rentBook() {
Book book = createDummyBook();
User user = createDummyUser();
BookRentals bookToRent = createDummyRentedBook(user, book);
when(userRepository.doesAccountExistsWithGivenID(user.getId())).thenReturn(true);
when(bookRepository.doesBookExistsWithGivenID(book.getId())).thenReturn(true);
when(bookRepository.findOne(book.getId())).thenReturn(book);
when(userRepository.findOne(user.getId())).thenReturn(user);
String expected = "Book was rented";
assertEquals(expected, bookRentalService.rentBook(user.getId(), book.getId()));
verify(bookRentalsRepository, times(1)).save(bookToRent);
}
STACKTRACE:
Argument(s) are different! Wanted:
bookRentalsRepository.save(
bookrental.model.book.BookRentals#7574b32f
);
-> at bookrental.service.book.rentals.BookRentalServiceTest.rentBook(BookRentalServiceTest.java:48)
Actual invocation has different arguments:
bookRentalsRepository.save(
bookrental.model.book.BookRentals#1c62c511
);
-> at bookrental.service.book.rentals.BookRentalService.rentBook(BookRentalService.java:36)
Comparison Failure: <Click to see difference>
Argument(s) are different! Wanted:
bookRentalsRepository.save(
bookrental.model.book.BookRentals#7574b32f
);
-> at bookrental.service.book.rentals.BookRentalServiceTest.rentBook(BookRentalServiceTest.java:48)
Actual invocation has different arguments:
bookRentalsRepository.save(
bookrental.model.book.BookRentals#1c62c511
);
-> at bookrental.service.book.rentals.BookRentalService.rentBook(BookRentalService.java:36)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:488)
at bookrental.service.book.rentals.BookRentalServiceTest.rentBook(BookRentalServiceTest.java:48)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
From the stack trace, it seems it fails because you didn't mock also the user repository.
Add the following:
#Mock
UserRepository userRepository;
...
when(userRepository.doesAccountExistsWithGivenID(user.getId()).thenReturn(true);

How to solve internal error from server (test)?

guys. I'm testing method and in test it's name is testGetAuthorizedUserPublicInfo. This method have to return an User object. (So i created getUser method which return our new user).
Then after calling some methods on mockMvc objects try to perform get method (url is the same like in Controller class).
But i getting 500 response (instead of 200).
Can anyone say where is my mistake?? it would be really great )
`
package com.softserve.academy.spaced.repetition.controller;
import com.softserve.academy.spaced.repetition.controller.handler.ExceptionHandlerController;
import com.softserve.academy.spaced.repetition.domain.Account;
import com.softserve.academy.spaced.repetition.domain.Person;
import com.softserve.academy.spaced.repetition.domain.User;
import com.softserve.academy.spaced.repetition.domain.enums.AccountStatus;
import com.softserve.academy.spaced.repetition.domain.enums.AuthenticationType;
import com.softserve.academy.spaced.repetition.domain.enums.ImageType;
import com.softserve.academy.spaced.repetition.domain.enums.LearningRegime;
import com.softserve.academy.spaced.repetition.service.UserService;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.context.MessageSource;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.Date;
import java.util.Locale;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(MockitoJUnitRunner.class)
public class UserControllerTest {
private MockMvc mockMvc;
private static final long USER_ID = 1L;
#InjectMocks
UserController userController;
#Mock
UserService userService;
#Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(userController)
.setControllerAdvice(new ExceptionHandlerController())
.build();
}
#Test
public void testGetAuthorizedUserPublicInfo() throws Exception {
when(userService.getAuthorizedUser()).thenReturn(getUser());
mockMvc.perform(get("/api/user/details")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", Matchers.is(1)));
}
private User getUser() {
Account account;
Person person;
User user;
account = new Account();
account.setId(USER_ID);
account.setPassword("12345678");
account.setEmail("a#a.a");
account.setAuthenticationType(AuthenticationType.LOCAL);
account.setStatus(AccountStatus.ACTIVE);
account.setDeactivated(false);
account.setLastPasswordResetDate(new Date());
account.setLearningRegime(LearningRegime.BAD_NORMAL_GOOD_STATUS_DEPENDING);
account.setCardsNumber(1);
person = new Person();
person.setId(USER_ID);
person.setFirstName("firstname");
person.setLastName("lastname");
person.setImageType(ImageType.NONE);
user = new User();
user.setId(USER_ID);
user.setAccount(account);
user.setPerson(person);
return user;
}
}
`
here is what i've got after executing this test method
`
java.lang.AssertionError: Status
Expected :200
Actual :500
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:664)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at com.softserve.academy.spaced.repetition.controller.UserControllerTest.testGetAuthorizedUserPublicInfo(UserControllerTest.java:71)
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:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Process finished with exit code 255
`

Not able to access File with Singleton pattern

I wrote java class that simulate Hard disk using file .
The Hard disk calss is Singleton . I am now using Junit to test some other class in the project and need to use the Hard disk calss .
From some reason every time I use the method HardDisk.getInstance();
in the Junit I get the error IOException. if I delete the file the error changes to fileNotFound, so I know the class is kinda of working .
Class Junit
import com.hit.algorithm.IAlgoCache;
import com.hit.algorithm.LRUAlgoCacheImpl;
import com.hit.memoryunits.*;
import junit.framework.Assert;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
public class MemoryManagementUnitTest {
#Test
public void testGetPages() throws IOException {
HardDisk.getInstance();
}
}
class Hard Disk
package com.hit.memoryunits;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
public class HardDisk{
static final String DEFAULT_FILE_NAME="src\\main\\test\\hdPages.txt";
static final int _SIZE=1000;
//private static final HardDisk instance=new HardDisk();
private static HardDisk instance=new HardDisk();
LinkedHashMap<Long,Page<byte[]>> harDiskMap;
#SuppressWarnings({ "unchecked"})
private HardDisk(){
harDiskMap = new LinkedHashMap<>(_SIZE);
try{
FileInputStream fis = new FileInputStream(DEFAULT_FILE_NAME);
ObjectInputStream in = new ObjectInputStream(fis);
try{
while(true){
Page<byte[]> temp = (Page<byte[]>)in.readObject();
harDiskMap.put(temp.getPageId(), temp);
}
}
finally{
in.close();
}
}
catch (ClassNotFoundException e){
System.out.println("ClassNotFoundException");
}
catch (FileNotFoundException e1){
System.out.println("FileNotFoundException");
}
catch(IOException e2){
System.out.println("IOException");
}
}
public static HardDisk getInstance(){
return HardDisk.instance;
}
private void writeHd() throws FileNotFoundException, IOException{
ObjectOutputStream out= new ObjectOutputStream(new FileOutputStream(DEFAULT_FILE_NAME));
for(Entry<Long, Page<byte[]>> entry : harDiskMap.entrySet()) {
Long key = entry.getKey();
out.writeObject(harDiskMap.get(key));
}
out.close();
}
public Page<byte[]> pageFault(Long pageId)throws FileNotFoundException,IOException{
if(!this.harDiskMap.containsKey(pageId))
this.harDiskMap.put(pageId, new Page<byte[]>( new byte[]{}, pageId));
Page<byte[]> temp=this.harDiskMap.get(pageId);
return temp;
}
public Page<byte[]> pageReplacement(Page<byte[]> moveToHdPage,Long moveToRamId) throws java.io.FileNotFoundException,java.io.IOException{
harDiskMap.replace(moveToHdPage.getPageId(), moveToHdPage);
writeHd();
return pageFault(moveToRamId);
}
}
Hi this the output
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at com.hit.memoryunits.HardDisk.<init>(HardDisk.java:26)
at com.hit.memoryunits.HardDisk.<clinit>(HardDisk.java:17)
at com.hit.memoryunits.MemoryManagementUnitTest.testGetPages(MemoryManagementUnitTest.java:33)
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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
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)

How do I set up class in PageObject?

I'm new in Selenium, I use IntelliJ, Selenium WebDriver, Junit. My problem is set up TestBase class in PageObject. This is my TestBase class:
package TestBaseSetup;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class TestBase {
WebDriver driver;
public WebDriver getDriver() {
return driver;
}
#Before
public void testSetUp(){
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Dragana\\Desktop\\chromedriver.exe ");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized", "--disable-cache");
driver = new ChromeDriver(options);
driver.navigate().to("http://store.demoqa.com/");
}
#After
public void testTearDown(){
driver.close();
}
}
This is my test class:
package test;
import PageObjectPage.HomePage;
import PageObjectPage.LogInResultPage;
import PageObjectPage.MyAccount;
import TestBaseSetup.TestBase;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
public class AccountTest extends TestBase {
protected WebDriver driver;
public WebDriver getDriver() {
return driver;
}
#Test
public void shouldLogIn() {
HomePage onHomePage = new HomePage(driver);
System.out.println("Step 1 ");
MyAccount onMyAccount = onHomePage.clickOnMyAccount();
System.out.println("Step 2");
LogInResultPage onResultPage = onMyAccount.LogIn().submitForm();
System.out.println("Step 3");
wait(2000);
Assert.assertTrue(onResultPage.getMessage().contains("ERROR"));
}
public void wait(int seconds){
try {
Thread.sleep(2000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
These are page in PageObject:
HomePage page:
package PageObjectPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class HomePage {
private WebDriver driver;
public HomePage(WebDriver driver){
this.driver=driver;
}
public MyAccount clickOnMyAccount(){
//Click on My Account
driver.findElement(By.className("account_icon")).click();
return new MyAccount(driver);
}
//public HomePage navigateToWebApp(){
// return new HomePage();
//}
public void wait(int seconds){
try {
Thread.sleep(2000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
MyAccount page:
package PageObjectPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class MyAccount {
protected WebDriver driver;
public MyAccount(WebDriver driver){
this.driver = driver;
}
public MyAccount LogIn(){
//Fill in the text box username
driver.findElement(By.id("log")).sendKeys("Dragana");
//Fill in the text box password
driver.findElement(By.id("pwd")).sendKeys("123456");
return new MyAccount(driver);
}
public LogInResultPage submitForm() {
//Click on button Log in
driver.findElement(By.id("login")).click();
return new LogInResultPage();
}
}
LogInResultPage page:
package PageObjectPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LogInResultPage {
protected WebDriver driver;
public LogInResultPage(){
}
public String getMessage(){
//Printing message
return driver.findElement(By.tagName("p")).getText();
}
}
My problem is when I run test outputs this:
"C:\Program Files\Java\jdk1.8.0_101\bin\java" -ea -Didea.launcher.port=7533 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.2.1\bin" -Didea.junit.sm_runner -Dfile.encoding=UTF-8 -classpath "C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.2.1\lib\idea_rt.jar;C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.2.1\plugins\junit\lib\junit-rt.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\rt.jar;C:\Users\Dragana\workspace\proba\target\test-classes;C:\Users\Dragana\.m2\repository\junit\junit\4.12\junit-4.12.jar;C:\Users\Dragana\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-java\3.0.0-beta3\selenium-java-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-chrome-driver\3.0.0-beta3\selenium-chrome-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-remote-driver\3.0.0-beta3\selenium-remote-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-api\3.0.0-beta3\selenium-api-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\cglib\cglib-nodep\3.2.4\cglib-nodep-3.2.4.jar;C:\Users\Dragana\.m2\repository\org\apache\commons\commons-exec\1.3\commons-exec-1.3.jar;C:\Users\Dragana\.m2\repository\com\google\code\gson\gson\2.3.1\gson-2.3.1.jar;C:\Users\Dragana\.m2\repository\com\google\guava\guava\19.0\guava-19.0.jar;C:\Users\Dragana\.m2\repository\org\apache\httpcomponents\httpclient\4.5.2\httpclient-4.5.2.jar;C:\Users\Dragana\.m2\repository\org\apache\httpcomponents\httpcore\4.4.4\httpcore-4.4.4.jar;C:\Users\Dragana\.m2\repository\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;C:\Users\Dragana\.m2\repository\commons-codec\commons-codec\1.9\commons-codec-1.9.jar;C:\Users\Dragana\.m2\repository\org\apache\httpcomponents\httpmime\4.5.2\httpmime-4.5.2.jar;C:\Users\Dragana\.m2\repository\net\java\dev\jna\jna\4.1.0\jna-4.1.0.jar;C:\Users\Dragana\.m2\repository\net\java\dev\jna\jna-platform\4.1.0\jna-platform-4.1.0.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-edge-driver\3.0.0-beta3\selenium-edge-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-firefox-driver\3.0.0-beta3\selenium-firefox-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-ie-driver\3.0.0-beta3\selenium-ie-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-opera-driver\3.0.0-beta3\selenium-opera-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-safari-driver\3.0.0-beta3\selenium-safari-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\io\netty\netty\3.5.7.Final\netty-3.5.7.Final.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-support\3.0.0-beta3\selenium-support-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\com\codeborne\phantomjsdriver\1.3.0\phantomjsdriver-1.3.0.jar" com.intellij.rt.execution.application.AppMain com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 test.AccountTest,shouldLogIn
Starting ChromeDriver 2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed) on port 9660
Only local connections are allowed.
Dec 05, 2016 3:41:11 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
Dec 05, 2016 3:41:38 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Step 1
java.lang.NullPointerException
at PageObjectPage.HomePage.clickOnMyAccount(HomePage.java:18)
at test.AccountTest.shouldLogIn(AccountTest.java:26)
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:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
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:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Process finished with exit code -1
I don't know where is problem when I run this project. Thanks.
You need to use PageFactory in order to use PageObjects, for example in PageObjectPage.HomePage.clickOnMyAccount(MyAccount.java:18)
you should return something like this:
return PageFactory.initElements(getDriver(), SettingsPage.class);
and when you start your test, the first page should be initialize like this:
HomePage onHomePage = PageFactory.initElements(driver, HomePage .class);
and create a PageBase class(all pages (Home, Account need to extend this), with something like this:
protected WebDriver driver;
public PageBase(WebDriver driver){
this.driver = driver;
}
public WebDriver getDriver() {
return this.driver;
}
with this you can remove all the:
private WebDriver driver;
in the pages.
Also the Pages that extends PageObjects should be initialize like this:
public HomePage(WebDriver driver) {
super(driver);
}
This is my TestBase set up class:
package TestBaseSetup;
import PageObjectPage.BasePage;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class TestBase {
WebDriver driver;
#Before
public void testSetUp(){
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Dragana\\Desktop\\chromedriver.exe ");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized", "--disable-cache");
driver = new ChromeDriver(options);
driver.navigate().to("http://store.demoqa.com/");
}
#After
public void testTearDown(){
driver.close();
}
}
This is BasePage class:
package PageObjectPage;
import org.openqa.selenium.WebDriver;
public class BasePage {
protected WebDriver driver;
public BasePage (WebDriver driver){
this.driver = driver;
}
public WebDriver getDriver() {
return this.driver;
}
}
These are pages in PageObject:
HomePage:
package PageObjectPage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
public class HomePage extends BasePage {
#FindBy(how = How.CLASS_NAME, using = "account_icon")
#CacheLookup
WebElement button_my_accout;
public HomePage(WebDriver driver){
super(driver);
}
public MyAccount clickOnMyAccount(){
//Click on My Account
button_my_accout.click();
return PageFactory.initElements(getDriver(), MyAccount.class);
}
}
MyAccount page:
package PageObjectPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class MyAccount extends BasePage {
#FindBy(id = "log")
#CacheLookup
WebElement username;
#FindBy(how = How.ID, using = "pwd")
#CacheLookup
WebElement password;
#FindBy(how = How.ID, using = "login")
#CacheLookup
WebElement login_button;
public MyAccount(WebDriver driver){
super(driver);
}
public MyAccount LogIn(){
//Fill in the text box username
username.sendKeys("Dragana");
//Fill in the text box password
password.sendKeys("123456");
return new MyAccount(driver);
}
public LogInResultPage submitForm() {
//Click on button Log in
login_button.click();
return new LogInResultPage(driver);
}
}
LogInResultPage:
package PageObjectPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LogInResultPage extends BasePage{
public LogInResultPage(WebDriver driver){
super(driver);
}
public String getMessage(){
//Printing message
return driver.findElement(By.tagName("p")).getText();
}
}
This is test page:
package test;
import PageObjectPage.HomePage;
import PageObjectPage.LogInResultPage;
import PageObjectPage.MyAccount;
import TestBaseSetup.TestBase;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
public class AccountTest extends TestBase {
WebDriver driver;
#Test
public void shouldLogIn() {
HomePage onHomePage = PageFactory.initElements(driver, HomePage.class);
System.out.println("Step 1 ");
MyAccount onMyAccount = onHomePage.clickOnMyAccount();
System.out.println("Step 2");
LogInResultPage onResultPage = onMyAccount.LogIn().submitForm();
System.out.println("Step 3");
wait(2000);
Assert.assertTrue(onResultPage.getMessage().contains("ERROR"));
}
public void wait(int seconds){
try {
Thread.sleep(2000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
This is a problem:
java.lang.NullPointerException
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.$Proxy8.click(Unknown Source)
at PageObjectPage.HomePage.clickOnMyAccount(HomePage.java:25)
at test.AccountTest.shouldLogIn(AccountTest.java:23)
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:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
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:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Process finished with exit code -1
In your test script you have not initialised WebDriver hence there is issue. For e.g. in AccountTest , driver which is being used is not initialised. You can put a debug point and check its value. Or else in constructor of your TestBase , you can initialise it and then try to execute. It should work then.
Like below:
public TestBase(){
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized", "--disable-cache");
driver = new ChromeDriver(options);
}
Let me know if that approach helps or need any help

Categories