首先添加依赖包:
保证仓库为jcenter()
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
下载jar包:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support:recyclerview-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'mysql:mysql-connector-java:5.+'
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-all:2.+'
}
测试代码:
package app.hwb.com.hiaiframework;
import org.junit.Before;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="
http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
public List<String> mockedList;
@Before
public void Init(){
mockedList = mock(List.class);
System.out.println("in the Init");
}
@Test
public void addition_isCorrect() throws Exception {
//Junit单元测试
assertEquals(4, 2 + 2);
//创建mock对象,参数可以是类,也可以是接口
//List<String> mockedList = mock(List.class);
mockedList.add("one");
//设置方法的预期返回值
when(mockedList.get(0)).thenReturn("hhh");
System.out.println(mockedList.size());
verify(mockedList).size();//验证方法调用(是否调用了size())
mockedList.clear();
try {
Class.forName("com.mysql.jdbc.Driver");
}catch (Exception e){
e.printStackTrace();
}
String url = "jdbc:mysql://10.12.13.88:3306/mysql";
Connection conn;
try{
conn = DriverManager.getConnection(url,"root","root");
Statement stmt = conn.createStatement();
System.out.println("Mysql数据库连接成功!");
String sql = "select * from user";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("User"+"\t"+"Password");
while (rs.next()){
System.out.print(rs.getString(2) + "\t");
System.out.print(rs.getString(3) + "\t");
System.out.println();
}
rs.close();
stmt.close();
conn.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
测试结果:
in the Init
0
Mysql数据库连接成功!
User
Password
root
*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B
root
*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B
Process finished with exit code 0
|
Java中单元测试(Junit4和Mockito)和数据库JDBC连接示例
最新推荐文章于 2025-06-19 09:18:29 发布