如何使用mockito测试数据库连接

Jug*_*ugi 5 junit jersey mockito rest-assured jersey-client

Junit用来测试我的球衣api.我想在没有数据库的情况下测试DAO.我尝试使用Mockito,但仍然无法使用模拟对象来测试包含Hibernate调用DB的DAO.我想写Junit一个调用DAO的Helper类.任何人都可以提供一些解决方案,其中包含一些示例代码来模拟DAO中的DB Connections.

编辑:

Status.java

@GET
@Produces(MediaType.TEXT_PLAIN)
public String getDBValue() throws SQLException {
    DatabaseConnectionDAO dbConnectiondao = new DatabaseConnectionDAO();
    String dbValue = dbConnectiondao.dbConnection();
    return dbValue;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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 );
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*tha 19

我想你可能会错过如何嘲笑DAO的想法.你不应该担心任何联系.一般来说,你只想模拟调用它的方法,比如调用findXxx方法.例如,假设你有这个DAO接口

public interface CustomerDAO {
    public Customer findCustomerById(long id);
}
Run Code Online (Sandbox Code Playgroud)

你可以嘲笑它

CustomerDAO customerDao = Mockito.mock(CustomerDAO.class);

Mockito.when(customerDao.findCustomerById(Mockito.anyLong()))
        .thenReturn(new Customer(1, "stackoverflow"));
Run Code Online (Sandbox Code Playgroud)

然后,您必须将该模拟实例"注入"依赖于它的类.例如,如果资源类需要它,您可以通过构造函数注入它

@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)
Run Code Online (Sandbox Code Playgroud)

不,当你点击findCustomer方法时,DAO将始终在模拟的DAO中返回Customer.

这是一个完整的测试,使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这个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>
Run Code Online (Sandbox Code Playgroud)

UPDATE

以上示例使用Jersey 1,因为我看到OP正在使用Jersey 1.有关使用Jersey 2(带注释注入)的完整示例,请参阅此帖子


Bri*_*ice 7

简短的回答就是不要!

需要进行单元测试的代码是DAO的客户端,因此需要模拟的是DAO.DAO是将应用程序与外部系统(此处为数据库)集成的组件,因此它们必须作为集成测试(即使用真实数据库)进行测试.