利用mock做service层单测

目标:不依赖外部(数据库,网络等),就能做业务层的单测。

只需要配上如下maven依赖(JUnit 4.0-4.3,其他版本的见官方文档):


1.6.3





org.mockito

mockito-core

1.10.19




org.powermock
powermock-module-junit4-legacy
${powermock.version} test


org.powermock
powermock-api-mockito
${powermock.version} test



示例代码:

import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

public class TestService {

  private TestDao testDao;

  public String testServiceMethod(Long id) {TestEntity entity = testDao.getById(id);

    if (entity.getUserId() == 1061L) { return "携程旅行网"; }

    if (entity.getUserId() == 1609L) { return "云娱";}

    return "";

  }

}

public class TestMock {

  @Test

  public void testMock() {

    //1.创建dao的mock

    TestDao testDao = mock(TestDao.class);

    TestEntity entity1 = new TestEntity();

    entity1.setUserId(1061L);

    entity1.setName("XX旅行网");

    TestEntity entity2 = new TestEntity();

    entity2.setUserId(1609L);

    entity2.setName("X娱");

    //2.定义行为,当调用dao的getById方法并且传入xx参数,则返回对应的entity

    when(testDao.getById(1061L)).thenReturn(entity1);

    when(testDao.getById(1609L)).thenReturn(entity2);

    //3.注入dao到service

    TestService testService = new TestService();

    try {

      Field declaredField = TestService.class.getDeclaredField("testDao");

      declaredField.setAccessible(true);

      ReflectionUtils.setField(declaredField, testService, testDao);

    } catch (Exception e) {

      e.printStackTrace();

      Assert.fail();

    }

    //4.验证service功能

    Assert.assertTrue(testService.testServiceMethod(1061L).equals("XX旅行网"));

    Assert.assertTrue(testService.testServiceMethod(1609L).equals("X娱"));

  }

}


背后实现原理可见:http://www.infoq.com/cn/articles/mockito-design

例子参见 http://blog.csdn.net/jackiehff/article/details/14000779,官方文档  https://github.com/jayway/powermock

eclipse+jkd1.7运行可能会报错,需要加个VM启动参数-XX:-UseSplitVerifier,具体可见http://blog.triona.de/development/jee/how-to-use-powermock-with-java-7.html

你可能感兴趣的:(测试工具)