StoreCode
StoreCode

Reputation: 155

Java - JUnit Test - ArrayList

I wrote a class to find the files walking into directory and subdirectory:

public class DirectoryWalker {

    public List<File> walk(String path) {

        File root = new File(path);
        List<File> resultList = new ArrayList<>();
        File[] list = root.listFiles();
        resultList.addAll(Arrays.asList(list));
            if (list == null) return null;

        for (File f : list) {
            if (f.isDirectory()) {
                walk(f.getAbsolutePath());
                System.out.println("Dir:" + f.getAbsoluteFile());
            } else {
                System.out.println("File:" + f.getAbsoluteFile());
            }
        }
        return resultList;
    }
}

Now I am trying to do the test using JUnit:

@Test
public void ListOfTheFiles(){

    List<File> result  = directoryWalker.walk("path");
    Assert.assertEquals(Arrays.asList("path\start.fxml"), result);

The test complains that:

    Expected :java.util.Arrays$ArrayList<[path\start.fxml]> 
Actual :java.util.ArrayList<[path\start.fxml]>

How I can test correctly the ArrayList in this case?

Upvotes: 1

Views: 1109

Answers (2)

Maciej Kowalski
Maciej Kowalski

Reputation: 26492

I would suggest using specialized libraries for assertions, especially not trivial ones like yours.

Try hamcrest:

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

then in your test:

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
....

@Test
public void ListOfTheFiles(){

  List<File> result  = directoryWalker.walk("path");
  assertThat(Arrays.asList(new File("path\\start.fxml")), is(result));

Update:

you need to add a File instead of a String as the first argument though

Upvotes: -1

Ousmane D.
Ousmane D.

Reputation: 56393

as mentioned by Dawood ibn Kareem within the comments, it seems like you're comparing two lists that contain different type of objects, i.e one is a List<File> and the other is a List<String> hence why they will never be equal. You'll need to make sure you're either performing the Assert on a List<File> objects against another List<File> objects or a List<String> against another List<String> objects but not different types.

Also, this string:

"path\start.fxml"

has to be changed to this:

"path\\start.fxml"

to escape the literal \

Upvotes: 4

Related Questions