这是模拟库的一个很好的用例。我用模仿。假设你想测试你的 DAO 客户端的行为,你只需模拟它:
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import junit.framework.Assert;
import org.junit.Test;
public class MockitoTest {
/** your dao, just putting some code here for an example */
class MyDAO {
public List<SVCAttribute> selectAll(Connection con) throws DAOException {
try {
//your code..
}catch(Exception ex) {
throw new DAOException();
}
return new ArrayList<SVCAttribute>();
}
}
@Test
public void testMe() throws Exception {
MyDAO dao = mock(MyDAO.class);
when(dao.selectAll(any(Connection.class))).thenThrow(DAOException.class);
Connection con = getConnection();
try {
dao.selectAll(con);
Assert.fail();
}catch(Exception ex) {
System.out.println("caught expected excetpion");
}
}