I'm writing a test case where I'm trying to use mockito to avoid entering text through console. But on running the test case, it waits for something to be entered in console (which is again something I'm unable to do) instead of getting it from mockito. Would appreciate if someone can help. The test code looks like this:
SongsNameUpdater songsNameUpdater = new SongsNameUpdater();
bufferedReader = mock(BufferedReader.class);
when(bufferedReader.readLine()).thenReturn("test Path");
songsNameUpdater.updateSongNames();
The main code is:
public class SongsNameUpdater {
public void updateSongNames() throws IOException {
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String path = bufferedReader.readLine();
System.out.println(path);
}
}
You have to pass your BufferedReader mock e.g. like updateSongNames(bufferedReader) and not instantiating it within the method
Related
Should I add a method and do not call throws in main?
Is that appropriate?
How do I write it? I do not know how to write.
private static String fileName = "C:\\fruit.csv";
public static void main(String[] args) throws
IOException{
BufferedReader br = new BufferedReader(new
FileReader(fileName));
TreeMap<String,Integer> tm = new
TreeMap<String,Integer>();
String line;
Logger logger = Logger.getLogger("Sample");
BasicConfigurator.configure();
logger.setLevel(Level.DEBUG);
try{
while((line = br.readLine()) != null){
String[] words = line.split("\\s");
for(String s : words){
if(!tm.containsKey(s)){
tm.put(s,1);
logger.debug(s+""+tm.get(s)+"N");}else{
tm.put(s,tm.get(s).intValue()+1);
logger.debug(s+""+tm.get(s)+"N");}}}
}catch(IOException e){
logger.debug("Error");
}finally{ br.close()}
Writer fw = new FileWriter("C:\\count.properties");
Properties p =new Properties();
for(String key : tm.keySet()){
p.setProperty(key,String.valueOf(tm.get(key)));
}p.store(fw,"fruit");}}}
Why is it inappropriate? Who says it is?
It entirely depends on the program, so broadly claiming that "it is inappropriate to throws at main" is wrong1.
What do you think should happen if an exception occurs? It is your decision to make, and the decision likely depends heavily on the purpose of the program.
It is an exception, so you likely want it printed, with a stacktrace so you can figure out where and why. Which is exactly what the java command does when main throws an exception, so why should you catch it, just to do the very same thing yourself?
Sure, if it is a command-line utility program, you'd likely want to catch the exception (including RuntimeException and Error), to print a one-line error message, without stacktrace, and then end the program with an exit code. But not all java programs are command-line utility programs.
1) Anyway, that is my opinion on the topic.
I need to physically print out my output box (using a printer) for a class.
Can someone please explain to me how to do this?
Instead of printing the console from eclipse, you can output all your System.out.println() directly to a file. Basically, you are using the file as a debugger instead of the console window. To do this, you can use the code below.
import java.io.*;
PrintWriter writer = new PrintWriter("debuggerOutput.txt", "UTF-8");
//in your class constructor, you will need to add some exception throws
write.println("I used to be in the debugger, but now I go in the file!!")
For each System.out.println(), add an extra write.println() with the same thing in the parenthesis so it outputs to the file what goes in the console.
Then, you will see all your output in a file that you can easily print.
At the end, make sure to write.close()
Full code:
import java.io.*;
public class test {
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter("myFile.txt", "UTF-8");
writer.println("The line");
writer.close();
}
}
I got below code in a method which I want to test
File f = map.get("key1")
BuffereReader r = new BufferedReader(new FileReader(f));
String line=null;
do {
line=r.readLine();
} while(r!=null);
I want to mock this operation so that I can pass the content of the file from the JUnit test case. I have done below:
Map fles = Mockito.mock(ConcurrentHashMap.class);
File file = Mockito.mock(File.class);
Mockito.when(files.get("key1")).thenReturn(file);
FileReader fileReader = Mockito.mock(FileReader.class);
BufferedReader bufferedReader = Mockito.mock(BufferedReader.class);
try {
PowerMockito.whenNew(FileReader.class).withArguments(file).thenReturn(fileReader);
PowerMockito.whenNew(BufferedReader.class).withArguments(fileReader).thenReturn(bufferedReader);
PowerMockito.when(bufferedReader.readLine()).thenReturn("line1")
.thenReturn("line2").thenReturn("line3");
} catch (Exception e) {
Assert.fail();
}
So basically I need to pass "line1", "line2" and "line3" as lines from the file which are read by the mocked BufferedReader.
However upon doing that, it failes as NullPointerException when trying to instantiate new FileReader(f) part.
So is it because I can't mock a BufferedReader or the approach is wrong?
Thanks
You could extract a method for doing the actual reading and then test that instead. That would mean you only have to mock a single reader. For example, your code would be something like this:
public void aMethod(){
File f = map.get("key1")
BuffereReader r = new BufferedReader(new FileReader(f));
readStuff(r);
}
public void readStuff(BufferedReader r){
String line=null;
do {
line=r.readLine();
} while(r!=null);
}
then your test code would be more like the following:
BufferedReader bufferedReader = Mockito.mock(BufferedReader.class);
Mockito.when(bufferedReader.readLine()).thenReturn("line1", "line2", "line3");
objUnderTest.readStuff(bufferedReader);
//verify result
You can try PowerMock annotations. Check this : https://code.google.com/p/powermock/wiki/MockConstructor
I am a beginner Java programmer, and I use this Java Tutorial.
In the I/O from the Command Line page, it uses InputStreamReader cin = new InputStreamReader(System.in); to get user input from the command line. But when I try to use it, nothing happens. I have a very simple program, and it's just to test whether this works, but it doesn't.
import java.io.*;
public class TestInput {
public static void main(String args[]) {
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
if(cin.equals("jon")) {
System.out.println("hello, jon.");
} else {
System.out.println("hello, guest.");
}
}
}
It just says, "hello, guest" and exits, without letting me input anything.
I'm assuming this is supposed to work similar to System.console, but if this isn't what it's supposed to be like, please tell me.
What is wrong with my code?
thanks for any answers.
EDIT
From the edits I'm getting, I suppose I have to use cin.readline() to actually read the input.
I got my program to work. thanks!
try{
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String name= cin.readLine();
if(name!=null && name.equals("jon")) {
System.out.println("hello, jon.");
} else {
System.out.println("hello, guest.");
}
}catch(IOException e){
}
You have to read the input:
if(cin.readLine().equals("jon")) { // or "jon".equals(...) to handle null
(See BufferedReader.readLine())
You will also have to handle the potential IOException with a try-catch.
With cin.equals("jon"), you are testing if the BufferedReader object cin is itself equal to the string "jon", which is clearly false.
You need to use, cin.readLine()
Oracle Docs.
if(cin.readLine().equals("jon"))
Also, you need to handle the IOException
The following code(when executed) prompts the user to enter any java class name to execute.
import java.io.*;
public class exec {
public static void main(String argv[]) {
try {
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter the java class name");
String s=br.readLine();
Process pro=Runtime.getRuntime().exec(s);
BufferedReader in=new BufferedReader(new InputStreamReader(pro.getInputStream()));
String line=null;
while((line=in.readLine())!=null) {
System.out.println(line);
}
in.close();
} catch(Exception err) {
err.printStackTrace();
}
}
This code works fine if I'm using command prompt and I'm able to execute another java program. But I'm unable to do the same using eclipse.No output or error is showing up once I enter the java class name.
I'm new to eclipse. Need help.
You can't "execute" a java class, so your code as posted can't work.
Instead, you'll need to execute "java" and pass to it the classpath and class name as parameters, something like this:
String s = br.readLine();
String[] cmd = {"java", "-cp", "/some/path/to/your/jar/file", s};
Process pro = Runtime.getRuntime().exec(cmd);
Do you just enter the name of the class, or do you also enter the directory of where the program is located? I think it doesn't work in eclipse because you need to specify where the file is... like C:\Users\Me\workspace\ProjectName\src\filename