Lucky
Lucky

Reputation: 53

Can I write unit test for following in spock?

public boolean accept(File directory, String fileName) {
    boolean fileOK = true;

    if (name != null) {
        fileOK &= fileName.startsWith(name);
    }

    if (pattern != null) {
        fileOK &= Pattern.matches(regex, fileName);
    }

    if (extension != null) {
        fileOK &= fileName.endsWith('.' + extension);
    }
    return fileOK;
}

Upvotes: 0

Views: 291

Answers (2)

Aravind Yarram
Aravind Yarram

Reputation: 80192

Below is another way of writing it. I used data-driven approach as you have to test multiple scenarios (multiple if's in the method)

def "should accept valid filenames"() {
    expect:
    foobar.accept(new File("/tmp"), fileName)

    where:
    fileName << ["valid_filename_1", "valid_filename_2", "valid_filename_n"]
}

Upvotes: 5

moskiteau
moskiteau

Reputation: 1102

Yes!

def "file should be valid"() {
    setup:
        def dir = new File("/tmp")
        def fileName = "foo.bar"

    when:
        boolean valid = foobar.accept(dir, fileName)

    then:
        valid
} 

Upvotes: 1

Related Questions