我正在使用Junit
测试我的球衣api。我想在没有数据库的情况下测试DAO。我尝试使用Mockito,但仍然无法使用模拟对象来测试包含Hibernate调用DB的DAO。我想为调用DAO的Helper类编写Junit
。任何人都可以使用一些示例代码提供解决方案来模拟DAO中的DB连接。
编辑:
Status.java
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getDBValue() throws SQLException {
DatabaseConnectionDAO dbConnectiondao = new DatabaseConnectionDAO();
String dbValue = dbConnectiondao.dbConnection();
return dbValue;
}
DatabaseConnectionDAO.java
private Connection con;
private Statement stmt;
private ResultSet rs;
private String username;
public String dbConnection() throws SQLException{
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
stmt = con.createStatement();
rs =stmt.executeQuery("select * from test");
while(rs.next()){
username = rs.getString(1);
}
}catch(Exception e){
e.printStackTrace();
}finally{
con.close();
}
return username;
}
TestDatabase.java
@Test
public void testMockDB() throws SQLException{
DatabaseConnectionDAO mockdbDAO = mock(DatabaseConnectionDAO.class);
Connection con = mock(Connection.class);
Statement stmt = mock(Statement.class);
ResultSet rs = mock(ResultSet.class);
Client client = Client.create();
WebResource webResource = client.resource("myurl");
ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
verify(mockdbDAO).dbConnection();
//when(rs.next()).thenReturn(true);
when(rs.getString(1)).thenReturn(value);
actualResult = response.getEntity(String.class);
assertEquals(expectedResult,actualResult );
}
答案 0 :(得分:18)
我想你可能错过了如何嘲笑DAO的想法。你不应该担心任何联系。通常,您只想模拟调用其方法时发生的事情,例如findXxx
方法。例如,假设你有这个DAO接口
public interface CustomerDAO {
public Customer findCustomerById(long id);
}
你可以像
一样嘲笑它CustomerDAO customerDao = Mockito.mock(CustomerDAO.class);
Mockito.when(customerDao.findCustomerById(Mockito.anyLong()))
.thenReturn(new Customer(1, "stackoverflow"));
然后,您必须将该模拟实例“注入”依赖于它的类。例如,如果资源类需要它,您可以通过构造函数
注入它@Path("/customers")
public class CustomerResource {
CustomerDAO customerDao;
public CustomerResource() {}
public CustomerResource(CustomerDAO customerDao) {
this.customerDao = customerDao;
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response findCustomer(@PathParam("id") long id) {
Customer customer = customerDao.findCustomerById(id);
if (customer == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return Response.ok(customer).build();
}
}
...
new CustomerResource(customerDao)
否,当您点击findCustomer
方法时,DAO将始终在模拟的DAO中返回客户。
这是一个完整的测试,使用Jersey测试框架
public class CustomerResourceTest extends JerseyTest {
private static final String RESOURCE_PKG = "jersey1.stackoverflow.standalone.resource";
public static class AppResourceConfig extends PackagesResourceConfig {
public AppResourceConfig() {
super(RESOURCE_PKG);
CustomerDAO customerDao = Mockito.mock(CustomerDAO.class);
Mockito.when(customerDao.findCustomerById(Mockito.anyLong()))
.thenReturn(new Customer(1, "stackoverflow"));
getSingletons().add(new CustomerResource(customerDao));
}
}
@Override
public WebAppDescriptor configure() {
return new WebAppDescriptor.Builder()
.initParam(WebComponent.RESOURCE_CONFIG_CLASS,
AppResourceConfig.class.getName()).build();
}
@Override
public TestContainerFactory getTestContainerFactory() {
return new GrizzlyWebTestContainerFactory();
}
@Test
public void testMockedDAO() {
WebResource resource = resource().path("customers").path("1");
String json = resource.get(String.class);
System.out.println(json);
}
}
Customer
类很简单,POJO包含long id
和String name
。泽西测试框架的依赖是
<dependency>
<groupId>com.sun.jersey.jersey-test-framework</groupId>
<artifactId>jersey-test-framework-grizzly2</artifactId>
<version>1.19</version>
<scope>test</scope>
</dependency>
以上示例使用Jersey 1,因为我看到OP正在使用Jersey 1.有关使用Jersey 2(带注释注入)的完整示例,请参阅this post
答案 1 :(得分:7)
简短回答不要!
需要进行单元测试的代码是DAO的客户端,因此需要模拟的是DAO。 DAO是将应用程序与外部系统(此处为数据库)集成的组件,因此它们必须作为集成测试(即使用真实数据库)进行测试。