I'm trying to test a function "DataFeatures" in my class "UserInput".
It doesn't matter what arguments I give in the test, It always pass.
Fields and constructor
public #Getter class UserInput {
FileType type;
FileOperation operation;
SynchronizationMethod method;
String path;
private static InputReader in = new InputReader();
public UserInput() {
// Dont need to do anything
}
Function to test
void getDataFeatures() {
System.out.println("For encryption press 1");
System.out.println("For decryption press 0");
operation = FileOperation.fromInt(in.nextInt());
System.out.println("For a file choose 1");
System.out.println("For an entire directory choose 0");
type = FileType.fromInt(in.nextInt());
if (type == FileType.DIR) {
System.out.println("For sync press 1");
System.out.println("For async press 0");
method = SynchronizationMethod.fromInt(in.nextInt());
}
}
My test
public class UserInputTest {
UserInput UI;
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream oldStdOut = System.out;
private final PrintStream oldStdErr = System.err;
private final InputStream oldStdIn = System.in;
#Before
public void initlize(){
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
UI = new UserInput();
}
#Test
public void getDataFeaturesTest() {
String data = "0" + "\n0" + "\n0";
System.setIn(new ByteArrayInputStream(data.getBytes()));
UI.getDataFeatures();
System.out.println(UI.getOperation());
assertThat(UI.getOperation(), is(equalTo(FileOperation.decryption)));
assertThat(UI.getType(), is(equalTo(FileType.FILE)));
assertThat(UI.getMethod(), is(equalTo(SynchronizationMethod.SYNC)));
}
#After
public void cleanUpStreams() {
System.setOut(oldStdOut);
System.setErr(oldStdErr);
System.setIn(oldStdIn);
}
}
Note 1: FileOperation, FileType and SynchronizationMethod are all enums that get 1 or 0.
Example of SynchronizationMethod:
public enum SynchronizationMethod {
SYNC(1), ASYNC(0);
private int method;
private SynchronizationMethod(int meth) {
this.method = meth;
}
public static SynchronizationMethod fromInt(int meth) {
for (SynchronizationMethod SM : SynchronizationMethod.values()) {
if (SM.method == meth) {
return SM;
}
}
throw new IllegalArgumentException("No constant with method " + meth + " found");
}
public String toString(){
if (method == 1){
return "Sync";
}
else if(method == 0){
return "ASync";
}
else{
throw new IllegalArgumentException("No constant with method " + method + " found in toString");
}
}
}
Solution
The problem was in the class InputReader in the constructor function.
public InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
}
The reader in this function and the Input Stream in the Junit function were disconnenct as suggested in the comments
Guessing here - your UserInput class says:
private static InputReader in = new InputReader();
Whereas your testcase says:
String data = "0" + "\n0" + "\n0";
System.setIn(new ByteArrayInputStream(data.getBytes()));
In other words: there might be a disconnect. Depending on the implementation behind InputReader you might simply be reading from the wrong source.
Related
I have 3 Classes: Regulate, Luminosity, Test
From the class Regulate, I which to setting an attribute in the class Luminosity by invoking the method setAttribute
Then in class Test, I calling the method getAttribute.
The problem is, When I calling the method getAttribute, I find a different value that I set it.
This is the Class Luminosity
public class Luminosity{
public static int attribute;
public static int getAttribute(){
return attribute;
}
public static void setAttribute(int v) {
attribute=v;
try {
File fichier = new File("../../WorkspaceSCA/Lamp/value.txt");
PrintWriter pw = new PrintWriter(new FileWriter(fichier)) ;
String ch=Integer.toString(attribute);
pw.append(ch);
pw.println();
pw.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
the Regulate Code:
public class Regulate {
public static void main(String[] args) throws InterruptedException {
Luminosity.setSensedValue(50));
System.out.println("Value of Luminosity= "+ Luminosity.getSensedValue());
}
}
this shows me: Value of Luminosity= 50
Now, I want to recover this value from a different class(Test), like this:
public class Test {
public static void main(String[] args) throws InterruptedException {
System.out.println("Value = "+ Luminosity.getSensedValue());
this shows me: Value= 0
I want to recover the same value.
Thank's in advance
You are start two different classes in two different threads.
Of course Luminosity doesn't have previous value, it was setting in different JVM.
If you want to setup an attribute and transfer it between two threads you can place it in a text file.
public class Luminosity {
private static final String FILE_NAME = "attribute.txt";
private int attribute;
public void writeAttribute(int val) throws IOException {
try (FileWriter fileWriter = new FileWriter(FILE_NAME)) {
fileWriter.append("" + val);
fileWriter.flush();
}
attribute = val;
}
public int readAttribute() throws IOException {
StringBuilder sb = new StringBuilder();
try (FileReader fileReader = new FileReader(FILE_NAME)) {
int r;
while (true) {
char[] buffer = new char[100];
r = fileReader.read(buffer);
if (r == -1) break;
sb.append(new String(Arrays.copyOf(buffer, r)));
}
} catch (FileNotFoundException e) {
return 0;
}
if (sb.length() == 0) return 0;
return Integer.parseInt(sb.toString());
}
public static void main(String[] args) throws IOException {
Luminosity luminosity = new Luminosity();
System.out.println("attribute after start: " + luminosity.readAttribute());
luminosity.writeAttribute(50);
System.out.println("new attribute: " + luminosity.readAttribute());
}
}
you may have seen my previous question, this builds on that with the implementation of a handler. however im finding it difficult to get it to work correctly.
i have three classes:
main.java
- simple method which requests to read console and then outputs the user input.
handler.java
- requests 'readconsole' from gui.java
gui.java
- displays gui
- reads console
feel like im missing something simple!
main.java
public class main {
static handler handler = new handler();
public static void main(String[] args) {
}
public static void menuSwitch(String input) {
System.out.println("entered menu switch with input " +input);
String s = handler.requestReadConsole();
System.out.println(s);
}
}
handler.java
public class handler {
static gui gui = new gui();
static String inputvariable= null;
public handler() {
requestAndSortReadConsole();
}
public String requestReadConsole() {
System.out.println("entered read console");
String s = gui.readConsole();
return s;
}
public String requestAndSortReadConsole() {
System.out.println("entered requestAndSortReadConsole");
sortInput(requestReadConsole());
System.out.println("sorted value = " + inputvariable);
return inputvariable;
}
public void sortInput(String input) {
System.out.println("entered sort input with input = " + input);
if (input.length() == 1) {
System.out.println("input length EQUALS 1");
main.menuSwitch(input);
}else {
inputvariable = input;
System.out.println(inputvariable);
}
System.out.println("return input");
}
}
gui.java
public class gui {
static Scanner in = new Scanner(System.in);
public gui() {
System.out.println("main menu called");
mainMenu();
}
public void mainMenu() {
System.out.println("press 1 for case 1");
System.out.println("press 2 for case 2");
System.out.println("press 3 for case 3");
}
public String readConsole () {
String input = null;
System.out.println("entered readconsole gui");
input = in.nextLine();
System.out.println("input = " + input);
in.close();
return input;
}
}
The method menuSwitch should print variable s but it doesnt print anything and continues to allow user to input to console!
For a testing course assignment, I need to create unit tests for my already-coded system using JUnit. My system is heavily dependent on each other and it also writes/reads from a couple of text files on my disk.
I realize I have to eliminate all dependancies to successfully unit test, I just don't know how to create stubs for Files.
Any help in code, tools or concepts is welcome
import Objs.*;
import java.io.*;
import java.net.URL;
import java.util.Scanner;
/**
*This class communicates with the users file by writing to it, reading from it, searching, deleting...
*
*/
public class users {
public static File usersFile = new File("usersFile.txt");
public static PrintWriter writer;
static Scanner read ;
public static void write(userObj u){
try {
String gather = read();
String newUser = u.toString();
writer = new PrintWriter(usersFile);
writer.append(gather).append(newUser).append("\n");
writer.close();
System.out.println("The users' file has been updated");
}
catch(FileNotFoundException ex){
System.out.print("file not found");
}
}
public static String read(){
String f = null;
try {
read = new Scanner(usersFile);
StringBuilder gather = new StringBuilder();
while(read.hasNext()){
gather.append(read.nextLine()).append("\n");
}
f = gather.toString();
}
catch(FileNotFoundException ex){
System.out.print("file not found");
}
return f;
}
public static userObj search(String s){
userObj foundUser = null;
try {
read = new Scanner(usersFile);
String st=null;
while(read.hasNext()){
if (read.next().equalsIgnoreCase(s)){
foundUser = new userObj();
foundUser.name = s;
foundUser.setType(read.next().charAt(0));
foundUser.credit = read.nextDouble();
}
}
}
catch(FileNotFoundException ex){
System.out.print("file not found");
}
return foundUser;
}
public static void remove(userObj u){
String s = u.name;
if (search(s) == null){
return;}
try {
read = new Scanner(usersFile);
StringBuilder gather = new StringBuilder();
while(read.hasNext()){
String info = read.nextLine();
if (info.startsWith(s)){
continue;
}
gather.append(info).append("\n");
}
writer = new PrintWriter(usersFile);
writer.append(gather).append("\n");
writer.close();
System.out.println("The user has been deleted");
}
catch(FileNotFoundException ex){
System.out.print("file not found");
}}
public static void update(userObj u){
remove(u);
write(u);
}
}
You don't need to create "stubs for files", you need to create "stub for reading from an InputStream".
For read, search, and remove you're using Scanner, which accepts an InputStream as one of its overloaded constructors. If you add an InputStream parameter, you can use that to construct your Scanner. With normal use, you can pass a FileInputStream, while using a StringBufferInputStream for testing.
For write and remove you're using a PrintWriter, which accepts an OutputStream as one of its overloaded constructors. If you add an OutputStream parameter, you can use that to construct your PrintWriter. With normal use, you can pass a FileOutputStream, while using a ByteArrayOutputStream for testing. If you want to read the result as a string from your test, use toString(String charsetName).
public class Users {
...
public static void write(UserObj u, InputStream input, OutputStream output) {
...
String gather = read(input);
...
writer = new PrintWriter(output);
...
}
public static String read(InputStream input) {
...
read = new Scanner(input);
...
}
public static UserObj search(String s, InputStream input) {
...
read = new Scanner(input);
...
}
public static void remove(UserObj u, InputStream input, OutputStream output) {
...
read = new Scanner(input);
...
writer = new PrintWriter(output);
...
}
public static void update(UserObj u, InputStream input, OutputStream output) {
remove(u, input, output);
write(u, input, output);
}
}
// Client code example
FileInputStream input = new FileInputStream("usersFile.txt");
FileOutputStream output = new FileOutputStream("usersFile.txt");
...
Users.write(myUser, input, output);
...
String result = Users.read(input);
...
myUser = Users.search(myString, input);
...
Users.remove(myUser, input, output);
...
Users.update(myUser, input, output);
// Testing code example
StringBufferInputStream input = new StringBufferInputStream("...");
ByteArrayOutputStream output = new ByteArrayOutputStream();
...
Users.write(myUser, input, output);
...
String result = Users.read(input);
...
myUser = Users.search(myString, input);
...
Users.remove(myUser, input, output);
...
Users.update(myUser, input, output);
...
result = output.toString("UTF-8"); // see docs for other legal charset names
I'm try to create one simple reservation system, we'll read a file, then we'll add Train, Bus, etc., then we'll writer everything to output.
import java.io.*;
import java.util.*;
public class Company
{
private static ArrayList<Bus> bus = new ArrayList<Bus>();
static int buscount = 0, traincount = 0;
public static void main (String[] args) throws IOException
{
FileParser();
}
public Company()
{
}
public static void FileParser()
{
try {
File file = new File(); //i fill this later
File file2 = new File(); // i fill this later
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file2);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
String line;
while ((line = br.readLine()) != null)
{
String[] splitted = line.split(",");
if(splitted[0].equals("ADDBUS"))
{
bus.add(buscount) = Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]);
}
}
}
catch (FileNotFoundException fnfe) {
}
catch (IOException ioe) {
}
}
}
I try to read the file line by line. For example one of the line is "ADDBUS,78KL311,10,140,54" I split the line for "," then i try to add every pieces of array to Bus' class' constructor but i couldn't figured it out.
My Bus Class is like `
public class Bus extends Vehicle{
private String command;
private String busName;
private String busPlate;
private String busAge;
private String busSpeed;
private String busSeat;
public Bus(String command, String busname, String busplate, String busage, String busspeed, String busseat)
{
this.command = command;
this.busName = busname;
this.busPlate = busplate;
this.busAge = busage;
this.busSpeed = busspeed;
this.busSeat = busseat;
}
public String getBusName() {
return busName;
}
public void setBusName(String busName) {
this.busName = busName;
}
public String getBusPlate() {
return busPlate;
}
public void setBusPlate(String busPlate) {
this.busPlate = busPlate;
}
public String getBusAge() {
return busAge;
}
public void setBusAge(String busAge) {
this.busAge = busAge;
}
public String getBusSpeed() {
return busSpeed;
}
public void setBusSpeed(String busSpeed) {
this.busSpeed = busSpeed;
}
public String getBusSeat() {
return busSeat;
}
public void setBusSeat(String busSeat) {
this.busSeat = busSeat;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
}
can someone show me a way to solve this problem?
Thank you,
You are missing the keyword new to create a new instance of the class:
bus.add(new Bus(...));
You can add items to ArrayList like this
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
you were missing new keyword before Bus constructor call. Then you can increment the counter (or do whatever)
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
buscount++;
try to add new Bus(...)
bus.add( new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
As I understand if you want to call constructor you need to call new Bus(parms).
when you say new it will call constructor of your class
when you say this() again it going to call enclosing class' constructor
if you say super() it will call super class' constructor.
if you want it into a map order by counter you can use this:
Map(Integer, Bus) busPosition = new HashMap<>();
busPosition.put(buscount, new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
I wrote a simple java application, I have a problem please help me;
I have a file (JUST EXAMPLE):
1.TXT
-------
SET MRED:NAME=MRED:0,MREDID=60;
SET BCT:NAME=BCT:0,NEPE=DCS,T2=5,DK0=KOR;
CREATE LCD:NAME=LCD:0;
-------
and this is my source code
import java.io.IOException;
import java.io.*;
import java.util.StringTokenizer;
class test1 {
private final int FLUSH_LIMIT = 1024 * 1024;
private StringBuilder outputBuffer = new StringBuilder(
FLUSH_LIMIT + 1024);
public static void main(String[] args) throws IOException {
test1 p=new test1();
String fileName = "i:\\1\\1.txt";
File file = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ";|,");
while (st.hasMoreTokens()) {
String token = st.nextToken();
p.processToken(token);
}
}
p.flushOutputBuffer();
}
private void processToken(String token) {
if (token.startsWith("MREDID=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("MREDID:").append(value).append("\n");
} else if (token.startsWith("DK0=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("DK0=:").append(value).append("\n");
} else if (token.startsWith("NEPE=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("NEPE:").append(value).append("\n");
}
if (outputBuffer.length() > FLUSH_LIMIT) {
flushOutputBuffer();
}
}
private String getTokenValue(String token,String find) {
int start = token.indexOf(find) + 1;
int end = token.length();
String value = token.substring(start, end);
return value;
}
private void flushOutputBuffer() {
System.out.print(outputBuffer);
outputBuffer = new StringBuilder(FLUSH_LIMIT + 1024);
}
}
I want this output :
MREDID:60
DK0=:KOR
NEPE:DCS
But this application show me this :
MREDID:60
NEPE:DCS
DK0=:KOR
please tell me how can i handle this , because of that DK0 must be at first and this is just a sample ; my real application has 14000 lines
Thanks ...
Instead of outputting the value when you read it, put it in a hashmap. Once you've read your entire file, output in the order you want by getting the values from the hashmap.
Use a HashTable to store the values and print from it in the desired order after parsing all tokens.
//initialize hash table
HashTable ht = new HashTable();
//instead of outputBuffer.append, put the values in to the table like
ht.put("NEPE", value);
ht.put("DK0", value); //etc
//print the values after the while loop
System.out.println("MREDID:" + ht.get("MREDID"));
System.out.println("DK0:" + ht.get("DK0"));
System.out.println("NEPE:" + ht.get("NEPE"));
Create a class, something like
class data {
private int mredid;
private String nepe;
private String dk0;
public void setMredid(int mredid) {
this.mredid = mredid;
}
public void setNepe(String nepe) {
this.nepe = nepe;
}
public void setDk0(String dk0) {
this.dk0 = dk0;
}
public String toString() {
String ret = "MREDID:" + mredid + "\n";
ret = ret + "DK0=:" + dk0 + "\n";
ret = ret + "NEPE:" + nepe + "\n";
}
Then change processToken to
private void processToken(String token) {
Data data = new Data();
if (token.startsWith("MREDID=")) {
String value = getTokenValue(token,"=");
data.setMredid(Integer.parseInt(value));
} else if (token.startsWith("DK0=")) {
String value = getTokenValue(token,"=");
data.setDk0(value);
} else if (token.startsWith("NEPE=")) {
String value = getTokenValue(token,"=");
data.setNepe(value);
}
outputBuffer.append(data.toString());
if (outputBuffer.length() > FLUSH_LIMIT) {
flushOutputBuffer();
}
}