[译]使用Mockito简单mock入门
我们在写单元测试的时候,面临的一个挑战就是要测试的内容总是依赖于其他组件,要是我们还得先配置好其他组件,未免有点不如意,那么我们可以使用Mocks来代替那些依赖的组件 本文问了展示这个过程,我会创建一个DAL,数据访问层,这是一个类,提供了一个通用的api来访问和修改数据仓库的数据,然后,我们要测试这个api,而不用配置连接某个本地的数据库,,或者一个远程的数据库,或者是一个文件系统,反正就是任何放数据的东西,DAL层的好处就是隔离开了数据访问和应用程序代码 首先使用maven来创建一个工程 mvn archetype:generate -DgroupId=info.sanaulla -DartifactId=MockitoDemo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 执行之后,本地生成MockitoDemo 文件夹,然后整个工程的目录结构与生成好了。 然后,我们写这样一个model类,表示book类型 package info.sanaulla.models; import java.util.List; /** * Model class for the book details. */ public class Book { private String isbn; private String title; private List<String> authors; private String publication; private Integer yearOfPublication; private Integer numberOfPages; private String image; public Book(String isbn, String title, List<String> authors, String publication, Integer yearOfPublication, Integer numberOfPages, String image){ this.isbn = isbn; this.title: = title; this.authors = authors; this.publication = publication; this.yearOfPublication = yearOfPublication; this.numberOfPages = numberOfPages; this.image = image; } public String getIsbn() { return isbn; } public String getTitle() { return title; } public List<String> getAuthors() { return authors; } public String getPublication() { return publication; } public Integer getYearOfPublication() { return yearOfPublication; } public Integer getNumberOfPages() { return numberOfPages; } public String getImage() { return image; } } 然后,我们访问Book model的DAL类会如下 package info.sanaulla.dal; import info.sanaulla.models.Book; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * API layer for persisting and retrieving the Book objects. */ public class BookDAL { private static BookDAL bookDAL = new BookDAL(); public List<Book> getAllBooks(){ return Collections.EMPTY_LIST; } public Book getBook(String isbn){ return null; } public String addBook(Book book){ return book.getIsbn(); } public String updateBook(Book book){ return book.getIsbn(); } public static BookDAL getInstance(){ return bookDAL; } } DAL层现在还没啥功能,我们要通过TDD来测试,实际中,DAL可能和ORM来交互,也可能和数据库API交互,但是我们设计DAL的时候,不用关心 ...