Issue
I've just started to learn java coding in college a month back. Here I'm just making a very simple program to reverse a string entered by the user.
For eg- if I enter "apple" it should return "elppa". However, my JUnit tests keep failing here. I tried using the debugger on the JUnit, but it just keeps throwing an exception java.lang.reflect.InvocationTargetException
.
I would really appreciate it if anyone here could help me fix this. Thanks in advance!! (Also please ignore my silly variable and class names, I was just messing around a bit)
public String word;
public wechillin (String wordin) {
word= wordin;
}
public void Reverse() {
String newword= "";
for (int i= word.length()-1; i>=0; i--) {
newword+= word.charAt(i);
}
word= newword;
}
Test:
@Test
public void testReverse() {
wechillin all = new wechillin("apple");
all.Reverse();
assertTrue(all.toString.equals("elppa"));
}
Solution
- First of all you can override toString method to return only word value.
@Override public String toString() { return word; }
I would recommend you to create getter for the value word and check this value in the unit test. Please see the following example:
public class wechillin { public String word; public wechillin (String wordin) { word= wordin; } public void Reverse() { String newword= ""; for (int i= word.length()-1; i>=0; i--) { newword+= word.charAt(i); } word= newword; } public String getWord() { return word; } }
And unit test:
class wechillinTest {
@Test
void reverse() {
wechillin all = new wechillin("apple");
all.Reverse();
assertTrue(all.getWord().equals("elppa"));
}
}
Answered By - Andrian Soluk