It is clear that I can't write the Test object to the file Test.dat, my question is what exactly is the reason that it will not succeed?
import java.io.*;
public class Test {
private int a = 10;
private double b = 7.5;
private String m = "valu";
public static void main(String[] args) {
Test t = new Test();
ObjectOutputStream output = ObjectOutputStream(new FileOutputStream("Test.dat"));
output.writeObject(t);
output.close();
}
}
Apart from new key word, you forgot to implement Serializable
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Test implements Serializable{
private int a = 10;
private double b = 7.5;
private String m = "valu";
public static void main(String[] args) throws IOException {
Test t = new Test();
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("Test.dat"));
output.writeObject(t);
output.close();
}
}
Try
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("Test.dat"));
You had missed the "new" so the compiler is looking for a static method rather than the constructor
Related
A reproducible example:
package test;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.Serializable;
public class mySerializable implements Serializable {
private static int f;
private static int g;
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("f", Integer.class),
new ObjectStreamField("g", Integer.class),
};
public static void main(String[] args) {
save();
}
public static void save() {
try {
FileOutputStream fileOut = new FileOutputStream("config" + ".ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(new mySerializable());
out.close();
fileOut.close();
} catch (Exception ex) {
System.out.println("save()" + ex.getLocalizedMessage()); }
}
public static int getF() {
return f;
}
public static void setF(int f) {
mySerializable.f = f;
}
public static int getG() {
return g;
}
public static void setG(int g) {
mySerializable.g = g;
}
}
The program prints:
save(): test.mySerializable; unmatched serializable field(s) declared
You've got two problems:
f and g are static; static fields aren't serialized.
They're also of type int, not Integer.
Make them non-static, and refer to them using int.class.
Ideone demo
//This is my Main Class here when i call methodTwo in this class i got numnodes=4 but when i tried to access methodTwo in testclass i got NullPointerException.
package Netica;
import norsys.netica.Environ;
import norsys.netica.Net;
import norsys.netica.NodeList;
import norsys.netica.Streamer;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import NeticaTestCases.HNetTest;
public class HNet {
private static long startTime = System.currentTimeMillis();
private static Net net;
private static NodeList nodes;
int numNodes;
public int methodOne() {
System.out.println("we are in first methodOne");
return 1;
}
public int methodTwo() {
numNodes = nodes.size();
System.out.println("we are in 2nd methodTwo");
return numNodes;
}
public static void main(String[] args) {
try {
// Read in the net file and get list of all nodes and also Total
// number of nodes:
net = new Net(neStreamer("DataFiles/KSA_4_Nodes_noisySum.dne"));
nodes = net.getNodes();
HNet temp = new HNet();
temp.methodOne();
System.out.println("numNodes========>"+temp.methodTwo());//get 4
} catch (Exception e) {
}
}
}
//this is my testclass
package NeticaTestCases;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.fail;
import Netica.HNet;
public class HNetTest {
HNet temp;
#Before
public void setUp() {
temp = new HNet ();
}
#Test
public void CheckNumNodes() {
temp.methodOne();
System.out.println("numNodes========>"+temp.methodTwo());
}
}
please help me out how to resolve NullPointerException in junit testcases.
Adding a statement initialising the nodes should get you rid of the exception -
#Before
public void setUp() {
temp = new HNet ();
temp.nodes = new NodeList();
}
Also, would suggest you to try and improve on few points -
Debug the difference between your main method and CheckNumNodes() test method.
Use of getters and setters
I have a class which implements Serializable and overrides its functions - writeObject and readObject.
How is it that while calling function readObject() there is no parameter passed but while defining the overridden there is a parameter. Its not even a parameter followed by any number of parameters signature [ like: (int i...)]
How is this code working:
//I understand this part:
package CustomizedSerialization;
import java.io.Serializable;
public class Cat implements Serializable
{
int k = 30;
int j = 10;
char c = 'c';
}
package CustomizedSerialization;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Dog2 implements Serializable
{
transient Cat c = new Cat();
private void writeObject(ObjectOutputStream oos) throws IOException
{
int x = c.j;
oos.writeInt(x);
}
*********marked line 1a - input parameter of readObject********
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException
{
ois.defaultReadObject();
c = new Cat();
}
}
package CustomizedSerialization;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeDemo2 {
public static void main(String[] args) throws IOException, ClassNotFoundException
{
Dog2 d = new Dog2();
System.out.println("Before serialization "+ d.c.j);
FileOutputStream fos = new FileOutputStream("C:\\serializedFile.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(d);
System.out.println("After serialization");
FileInputStream fis = new FileInputStream("C:\\serializedFile.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
*********marked line 1a - input parameter of readObject********
Dog2 d1 = (Dog2) ois.readObject();
System.out.println(d1.c.j);
System.out.println(d1.c.c);
}
}
How is "line marked 1 a" in programs (Dog2 and SerializeDemo2) working? SerializeDemo2 calls function readObject of class Dog2 without any parameter but while defining the called function (readObject) in class Dog2, it has an input parameter. How is it not throwing error.
ObjectInputStream.readObject() with no parameters calls the deserialized object's readObject(ObjectInputStream ois) method, if it exists, and that in turn should call ObjectInputStream.defaultReadObject(). These are three distinct methods, and none of them is an override of any other.
My problem is simple: I need to access variable history (which is declared in class BinaryServer) from another class.I'm using more classes to run this code.It's just simple client and server made of sockets.Client sends to server binary code/text and server translates it to text/binary code and sends it back to client.I can provide all classes if needed.
BinaryServer class
import java.net.*;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import graphics.gui;
public class BinaryServer extends gui implements ActionListener,Runnable
{
private ServerSocket server;
private Socket client;
public String text;
private BufferedReader reader;
public static ArrayList<String> history;
public static String binary_letter;
public static String[] letter;
public static int i;
public static String[] binary;
public static String sendback;
public static void main(String[] args)throws IOException
{
BinaryServer instance=new BinaryServer();
gui.buildframe(310,360,"Binary translator server");
gui.buildpane(300,300,true);
gui.buildbutton(300,20,"Translate");
instance.server(63400);
}
public void server(int port)throws IOException
{
history=new ArrayList<String>(100);
server=new ServerSocket(port);
button.addActionListener(this);
while(true)
{
client=server.accept();
reader=new BufferedReader(new InputStreamReader(client.getInputStream()));
text=reader.readLine();
history.add(text);
message.setText(message.getText()+"\n"+text+": ");
}
}
#Override
public void actionPerformed(ActionEvent e)
{
Thread response=new Thread(new BinaryServer());
if(text.contains("0"))
{
int length=text.length();
letter=new String[length+1];
sendback="";
int begin=-8;
int end=0;
for(i=1;i<=length/8;i++)
{
begin=begin+8;
end=i*8;
binary_letter=text.substring(begin,end);
Libary.translate();
message.setText(message.getText()+letter[i]);
sendback=sendback+letter[0+i];
}
}
else
{
int length=text.length();
letter=new String[length+1];
binary=new String[length+1];
sendback="";
for(i=1;i<=length;i++)
{
letter[i]=text.substring(i-1,i);
Libary.encode();
message.setText(message.getText()+binary[i]);
sendback=sendback+binary[0+i];
}
}
response.start();
}
public void run()
{
try
{
Socket feedback=new Socket("localhost",63403);
PrintWriter writer=new PrintWriter(feedback.getOutputStream(),true);
writer.println(sendback);
feedback.close();
return;
}
catch(IOException exc)
{
System.out.println("");
}
}
}
BinaryHistory class (The one I want access variable from)
public class BinaryHistory
{
public static void main(String[] args)
{
show();
}
public static void show()
{
System.out.println(BinaryServer.history);
}
When I access variable history from class BinaryHistory, it's alway null.
If you only declare the variable, regardless of the type or whether or not it's static, it will get a default value of null.
You have to initialize the variable too:
public static ArrayList<String> history = new ArrayList<>();
From the examples on the PowerMock homepage, I see the following example for partially mocking a private method with Mockito:
#RunWith(PowerMockRunner.class)
// We prepare PartialMockClass for test because it's final or we need to mock private or static methods
#PrepareForTest(PartialMockClass.class)
public class YourTestCase {
#Test
public void privatePartialMockingWithPowerMock() {
PartialMockClass classUnderTest = PowerMockito.spy(new PartialMockClass());
// use PowerMockito to set up your expectation
PowerMockito.doReturn(value).when(classUnderTest, "methodToMock", "parameter1");
// execute your test
classUnderTest.execute();
// Use PowerMockito.verify() to verify result
PowerMockito.verifyPrivate(classUnderTest, times(2)).invoke("methodToMock", "parameter1");
}
However, this approach does not seem to work when the private method we wish to mock is static. I wish to create a partial mock of the below class, with the readFile method mocked:
package org.rich.powermockexample;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import static com.google.common.io.Files.readLines;
public class DataProvider {
public static List<String> getData() {
List<String> data = null;
try {
data = readFile();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
private static List<String> readFile() throws IOException {
File file = new File("/some/path/to/file");
List<String> lines = readLines(file, Charset.forName("utf-8"));
return lines;
}
}
Please could someone let me know how this can be achieved?
After doing a bit more research, it seems that PowerMockito.spy() and PowerMockito.doReturn() are what is required here:
package com.richashworth.powermockexample;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
#RunWith(PowerMockRunner.class)
#PrepareForTest({DataProvider.class})
public class ResultsWriterTest {
private static List<String> mockData = new ArrayList<String>();
private ResultsWriter resultsWriter;
#BeforeClass
public static void setUpOnce() {
final String firstLine = "Line 1";
final String secondLine = "Line 2";
mockData.add(firstLine);
mockData.add(secondLine);
}
#Before
public void setUp() {
resultsWriter = new ResultsWriter();
}
#Test
public void testGetDataAsString() throws Exception {
PowerMockito.spy(DataProvider.class);
PowerMockito.doReturn(mockData).when(DataProvider.class, "readFile");
final String expectedData = "Line 1\nLine 2\n";
final String returnedString = resultsWriter.getDataAsString();
assertEquals(expectedData, returnedString);
}
}
For further details and the complete code listing, check out my blog post here: https://richashworth.com/post/turbocharge-your-mocking-framework-with-powermock/
Test class:
#RunWith(PowerMockRunner.class)
#PrepareForTest(DataProvider.class)
public class DataProviderTest {
#Test
public void testGetDataWithMockedRead() throws Exception {
mockStaticPartial(DataProvider.class, "readFile");
Method[] methods = MemberMatcher.methods(DataProvider.class, "readFile");
expectPrivate(DataProvider.class, methods[0]).andReturn(Arrays.asList("ohai", "kthxbye"));
replay(DataProvider.class);
List<String> theData = DataProvider.getData();
assertEquals("ohai", theData.get(0));
assertEquals("kthxbye", theData.get(1));
}
}
Class being tested (basically yours):
public class DataProvider {
public static List<String> getData() {
try {
return readFile();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static List<String> readFile() throws IOException {
File file = new File("/some/path/to/file");
return readLines(file, Charset.forName("utf-8"));
}
}
In general, only use static mocking for classes that are beyond your control (e.g. java.io.File). Since DataProvider and readFile are your own, refactor DataProvider into a proper class (i.e. make its methods non-static), pull out readFile into a helper object and then mock that. See this answer https://stackoverflow.com/a/8819339/116509.