Not able to access File with Singleton pattern - java

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)

Related

Nullpoint exception message Selenium springboot

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

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.)

java.lang.VerifyError: Cannot inherit from final class with spring websocket

I'm new in websocket with Spring,I have an error with my unit test
[java.lang.VerifyError: Cannot inherit from final class]
in the line SockJsClient sockJsClient = new SockJsClient(transports);.
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nullable;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.messaging.simp.stomp.StompFrameHandler;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;
import org.springframework.web.socket.sockjs.client.SockJsClient;
import org.springframework.web.socket.sockjs.client.Transport;
import org.springframework.web.socket.sockjs.client.WebSocketTransport;
import org.springframework.web.socket.sockjs.frame.Jackson2SockJsMessageCodec;
import com.pharmagest.entite.websocket.ServerMessage;
import com.pharmagest.guiriden.offidose.websocket.DefEndPoint;
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ProductionWebSocketServiceTest2 {
/**
* WebSocket parameters
*/
private static final String PORT = "9181";
private static final String URL_WEB_SOCKET = "ws://localhost:" + PORT + "/offidose";
/**
* Timeout to receive a response on a broker
*/
private static final int TIMEOUT = 200;
/**
* WebSocket session & Queue to stock data
*/
private StompSession stompSession;
private BlockingQueue<ServerMessage> blockingQueue;
#Before
public void setup() {
try {
blockingQueue = new LinkedBlockingQueue<>();
Transport webSocketTransport = new WebSocketTransport(new StandardWebSocketClient());
List<Transport> transports = Collections.singletonList(webSocketTransport);
SockJsClient sockJsClient = new SockJsClient(transports);
sockJsClient.setMessageCodec(new Jackson2SockJsMessageCodec());
WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
stompSession = stompClient.connect(URL_WEB_SOCKET, new StompSessionHandlerAdapter() {
}).get(TIMEOUT, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stompSession.subscribe(DefEndPoint.SUBSCRIBE_EXPORT_PROD, new DefaultStompFrameHandler(ServerMessage.class));
}
#Test
public void testWebSocketEndPointExportProd()
throws InterruptedException {
stompSession.send(DefEndPoint.SUBSCRIBE_EXPORT_PROD, new ServerMessage());
ServerMessage sm = blockingQueue.poll(TIMEOUT, TimeUnit.MILLISECONDS);
Assert.assertEquals("Hello World From Server", sm.getMessage());
}
private class DefaultStompFrameHandler
implements StompFrameHandler {
private Class respClass;
DefaultStompFrameHandler(final Class respClass) {
this.respClass = respClass;
}
#Override
public Type getPayloadType(final StompHeaders stompHeaders) {
return respClass;
}
#Override
public void handleFrame(final StompHeaders stompHeaders, #Nullable final Object o) {
if (o != null && o instanceof ServerMessage) {
blockingQueue.offer((ServerMessage) o);
}
}
}
}
The error:
java.lang.VerifyError: Cannot inherit from final class
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at com.fasterxml.jackson.datatype.jdk8.Jdk8Module.setupModule(Jdk8Module.java:30)
at com.fasterxml.jackson.databind.ObjectMapper.registerModule(ObjectMapper.java:524)
at org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.registerWellKnownModulesIfAvailable(Jackson2ObjectMapperBuilder.java:734)
at org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.configure(Jackson2ObjectMapperBuilder.java:624)
at org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.build(Jackson2ObjectMapperBuilder.java:608)
at org.springframework.web.socket.sockjs.frame.Jackson2SockJsMessageCodec.<init>(Jackson2SockJsMessageCodec.java:51)
at org.springframework.web.socket.sockjs.client.SockJsClient.<init>(SockJsClient.java:107)
at com.pharmagest.services.websocket.production.ProductionWebSocketServiceTest2.setup(ProductionWebSocketServiceTest2.java:67)
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.RunBefores.evaluate(RunBefores.java:24)
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:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Selenium java.lang.nullpointerexception JUnit Test Case

I have the following error and I would appreciate if someone can tell me what am I doing wrong. I'm trying to run test in navigateAllMenus.java but the moment the script tries to locate loginLink, it stops and gives me java.lang.NullPointerException in line 28:
_a_LoginPage.loginLink(driver).click();.
I have tried many times with different xpaths for the same element but nothing works. I am at a Jr level and still get confused with certain things. So here's what I have, thank you in advance.
Trace:
java.lang.NullPointerException
at autFwk.navigateAllMenus.test(navigateAllMenus.java:28)
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:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Test case:
package autFwk;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import pagObj._b_HomePage;
import pagObj._a_LoginPage;
public class navigateAllMenus {
#BeforeClass
public static void setUpBeforeClass() throws Exception {
System.setProperty("webdriver.chrome.driver","ChromeDriver/chromedriver.exe");
}
#Test
public void test() {
WebDriver driver = new ChromeDriver();
driver.get("https://www.interaction-design.org/");
_a_LoginPage.loginLink(driver).click();
_a_LoginPage.email(driver).sendKeys("em#ail.com");
_a_LoginPage.password(driver).sendKeys("password");
_a_LoginPage.loginButton(driver).click();
_b_HomePage.Profile(driver).click();
driver.navigate().back();
_b_HomePage.Courses(driver).click();
driver.navigate().back();
_b_HomePage.Community(driver).click();
driver.navigate().back();
_b_HomePage.Logout(driver).click();
assertTrue(_a_LoginPage.loginLink(driver).isDisplayed());
driver.quit();
}
}
Object loginLink is the one that seems to be giving me trouble:
package pagObj;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class _a_LoginPage {
private static WebElement element = null;
public static WebElement loginLink (WebDriver driver){
driver.findElement(By.xpath("//a[#href='https://www.interaction-design.org/login']"));
return element;
You are getting a NullPointerException because in the _a_LoginPage Class you haven't initialized the WebDriver instance i.e. driver and haven't written the constructor. So you have to add the following in the _a_LoginPage Class :
//initialize the WebDriver instance
WebDriver driver;
//constructor
public _a_LoginPage(WebDriver driver)
{
this.driver=driver;
}

Java Error: 'Throw new Exception not Supported'

I looked around and am a little confused if it is working or not. The result while debugging gives me the impression that it fails.
Statement 'throw new SessionTimeoutException("Session Timeout"); ' not supported
I am running a test case in Junit and have made many using exceptions previously already however they are implemented in the same manner as the method below at.
private void checkSessionTimeout(HtmlPage page) throws SessionTimeoutException {
I am new to Exceptions and do not understand why it only errors at runtime during the test.
My test runs and fails in the method inside the if statement
private void checkSessionTimeout(HtmlPage page) throws SessionTimeoutException {
HtmlDivision imgDivElement = page.getFirstByXPath("//div[#class='border']");
HtmlDivision errorDivElement = page.getFirstByXPath("//div[#class='error']");
String imgUrl = imgDivElement.getFirstElementChild().getAttribute("src");
String errorMessage = errorDivElement.getTextContent().trim();
if(page.getWebResponse().getContentAsString().contains(imgUrl) && page.getWebResponse().getContentAsString().contains(errorMessage)){
throw new SessionTimeoutException("Session Timeout");
}
}
At this line: throw new SessionTimeoutException("Session Timeout");
package com.cantShow;
import com.cantShow.htmlunit.html.HtmlPage;
import com.cantShow.TimeoutInformation;
import com.cantShow.AbstractScraperTest;
import com.cantShow.scrape.Scraper;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.cantShow.SessionTimeoutException;
public class ScraperTest extends ScraperTest<HtmlPage, SessionTimoutClassWithGettersSetters> {
#Override
protected Scraper<HtmlPage, SessionTimoutClassWithGettersSetters> getScraper() {
return new Scraper();
}
#Test
public void scrape() throws Exception {
SessionTimoutClassWithGettersSettersresult = testScraper("/scrape/timeout-session.html",
"https://cantShow.html");
details(result, "imgs/error.png","Your session has timed out. You will need to log back in to continue shopping.");
}
private static void details(SessionTimoutClassWithGettersS setterstimeoutInformation, String errorImgUrl, String errorMsg){
assertEquals(errorImgUrl, sessionTimoutClassWithGettersSetters.getErrorImageUrl());
assertEquals(errorMsg, sessionTimoutClassWithGettersSetters.getErrorMessage());
}
}
Stack Trace:
com.cantShow.Scraper.checkSessionTimeout(Scraper.java:28)
atcom.cantShow.Scraper.Scraper.scrape(Scraper.java:16)
at com.cantShow.Scraper.Scraper.scrape(Scraper.j va:12)
at com.cantShow.Scraper.ScrapeService.scrapeString(ScrapeService.java:406)
at com.cantShow.Scraper.AbstractScraperTest.testScraper(AbstractScraperTest.java:32)
at com.cantShow.Scraper.ScraperTest.scrape(ScraperTest.java:22)
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:497)
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.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
I have looked at other posts on Stack Overflow however could not find one like this for Java.
If you want to test that the Exception is thrown you have to catch it and verify that it is the right Exception.
#Test
public void scrape() throws Exception {
boolean exceptionHappend = false;
try {
SessionTimoutClassWithGettersSettersresult =
testScraper("/scrape/timeoutsession.html", "https://cantShow.html");
} catch (SessionTimeoutException e) {
exceptionHappend = true;
}
assertTrue(exceptionHappend);
details(result, "imgs/error.png","Your session has timed out. You will need to log back in to continue shopping.");
}

Categories