测试没有DAO的服务层

Osc*_*car 2 java testing junit spring mocking

你能给我一个例子,说明如何在没有使用模拟对象,Spring或任何其他框架的DAO的情况下测试我的服务层.我的Java代码如下所示:

public int myServiceMethod(int number) {

    int myInt = Factory.getDAOImpl.getNumber();
    return myInt + number * 8;
}
Run Code Online (Sandbox Code Playgroud)

我想测试myServiceMethod的逻辑,但不测试DAO方法.可能吗?我必须重构它吗?你能告诉我一个如何测试这个简单方法的例子.谢谢

ism*_*riv 6

在您的示例中,您只需要模拟DAO(例如使用Mockito),并修复要返回的数字.

DAOImpl myDao = mock(DAOImpl.class);
when(myDao.getNumber()).thenReturn(7);
Run Code Online (Sandbox Code Playgroud)

调用方法时getNumber,您将始终获得7.在创建服务时传递此DAO,并正常编写测试:

assertEquals(224, service.myServiceMethod(4));
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!