如何使用Spock框架在另一个类中调用时模拟类方法

时间:2017-12-20 19:22:29

标签: java groovy spock spring-boot-test

public class BookService {

    public BookService() {
    }

    public List<Book> listAvailableBooks() {

        List<Book> books = new ArrayList<Book>();
        Book book1 = new Book("The Color of Magic", "T. P.", true);
        Book book2 = new Book("There and Back Again", "B. B.", true);
        Book book3 = new Book("Do Androids Dream of Electric Sheep?", "P. K. D.", false);
        books.add(book1);
        books.add(book2);
        books.add(book3);
        return books;
    }
}

BookService在WorkService类中实例化。我如何模拟这个类的方法,因此它总是返回0.

listAvailableBooks(); //should always return 0;

WorkService类:

public class WorkService {

    public Integer listSize(){
        BookService bs = new BookService();
        return bs.listAvailableBooks().size();
    }
}

最后,这是我的spock groovy测试:

@SpringBootTest
class BookServiceTests extends Specification {

    //BookService bookService
    WorkService workService = new WorkService()
    BookService bookService

    def "returns no books if no books available"() {
        given: "no books"
        bookService = Stub()

        when: "retrieving available books"
        bookService.listAvailableBooks() >> new ArrayList<Book>()

        then: "there are no books available"
        workService.listSize() == 0//expecting 0, but returning 3
    }
}

0 个答案:

没有答案