Search code examples
javajunitjunit4

Trying to write a Junit test, but it's failing


Here is my code:

Concatenate.java

package concatenate;

import java.util.Scanner;

public class Concatenate {
    private static String firstWord;
    private static String secondWord;

    public Concatenate(String firstWord, String secondWord) {
        Concatenate.firstWord = firstWord;
        Concatenate.secondWord = secondWord;
    }

    public String getFirst() {
        return firstWord;
    }

    public String getSecond() {
        return secondWord;
    }

    public static Concatenate something() {
        Scanner myObj = new Scanner(System.in);
        System.out.println("Enter first word");
        firstWord = myObj.nextLine();
//        Scanner newObj = new Scanner(System.in);
        System.out.println("Enter second word");
        secondWord = myObj.nextLine();
        return new Concatenate(firstWord, secondWord);
    }

    public static void main(String[] args) {
        Concatenate result = something();
        System.out.println(result.getFirst() + " " + result.getSecond());
    }

}

ConcatenateTest.java

package concatenate;

import org.junit.Test;
import static org.junit.Assert.*;

public class ConcatenateTest {

    public ConcatenateTest() {
    }

    @Test
    public void testMain() {
        String firstWord = "Hello";
        String secondWord = "world";
        String expectedResult = "Hello world";
        Concatenate testResult = new Concatenate(firstWord, secondWord);
        assertEquals(expectedResult, testResult);
        assertEquals(1, 1);
    }
}

But when I run the test, it fails, and I get...

Expected <hello world> but was concatenate.Concatenate@[alphanumeric string]

Any pointers please?

BTW, I tried to copy all this over to Eclipse, but it threw a whole bunch of additional errors. If anyone could tell me why that would also be great. https://i.sstatic.net/koFKk.jpg

TIA


Solution

  • Since you are comparing String with Concatenate object. So it won't match.

    Better to create a concat method in the Concatenate class and assert the the output of the method

    public String concat() {
        return firstWord + " " + secondWord;}
    

    and compare

    assertEquals(expectedResult, testResult.concat());

    Hope this clarifies your question