说明:通过lookupSessionFactory()方法获取这个测试环境中的org.hibernate.SessionFactory实体对象,其中
applicationContext是org.springframework.context.ApplicationContext的实现org.springframework.context.support.GenericApplicationContext
我们可以通过它的getBean方法来获取你配置文件中配置的SessionFactory。使用注解是org.springframework.orm.hibernate4.annotation.AnnotationSessionFactoryBean
不需要使用注解的时候可以使用org.springframework.orm.hibernate.LocalSessionFactoryBean来实现。
该单元测试需要加载spring配置文件信息,默认加载路径是你项目的src目录下,文件名默认为applicationContext.xml,如果路径不对或者
文件名不同,则需要重写getContextLocations()方法,如
protected String getContextLocations() { return "classpath*:applicationContext.xml"; } |
关于实现web session的问题,很简单,该类提供了一个MockHttpServletRequest成员变量,我们只要mock一个session出来,然后加入到这个request中,就可以实现session的模拟了。示例代码如下:
HttpSession session = new MockHttpSession(); String sessionId = UUID.randomUUID().toString(); session.setAttribute(ConstParameter.USER_SESSION, sessionId); //user是一个用户信息的类,你可以根据你的需要自己定义 UserInfor user = new UserInfo(); user.setUserId(1); user.setName("xxx"); session.setAttribute(ConstParameter.USER_INFO, user); request.setSession(session); |
关于action的单元测试我们就说完了。
二、Service的单元测试
接下来我们在说说关于service的测试,
同样,我们先从依赖说起,需要添加的依赖:
<powermock.version>1.7.1</powermock.version> <!--********************powermock使用*********************--> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>${powermock.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>${powermock.version}</version> <scope>test</scope> </dependency> |
此处我们采用的是powermock+junit 进行mock测试。为啥使用powermock呢,毋庸置疑,由于他的功能比较强大
1、首先,我们我们看看待测试的代码:
@Override public List<MyInvoice> getMyInvoice(String buyerId) { if (StringUtils.isBlank(buyerId)) { return null; } List<MyInvoice> myInvoices = new ArrayList<MyInvoice>(); String url = baseDataUrl + UrlConfig.GET_MYINVOICE_URL + "?t=" + VerifyBaseUtil.getT() + "&token=" + VerifyBaseUtil.getToken() + "&buyerId=" + buyerId; System.out.println("MyInvoiceServiceImpl getMyInvoice接口请求参数为:" + url); try { String responseInfo = HttpUtil.getHttp(url); System.out.println("MyInvoiceServiceImpl getMyInvoice接口返回结果为:" + responseInfo); Map<String, Object> result = JSON.parseObject(responseInfo, Map.class); if (DistrictReturnNum.SUCCESS.getValue().equals(result.get("code"))) { myInvoices = JSON.parseArray(JSON.toJSONString(result.get("result")), MyInvoice.class); return myInvoices; } } catch (Exception e) { System.out.println("MyInvoiceServiceImpl getMyInvoice 程序出错,查询发票失败"+e.getMessage()); return null; } return null; } |
getMyInvoice方法是一个调用外部接口的方法,通过http协议进行通信。这儿有两个问题
1.HttpUtil.getHttp(url) 是一个静态方法,我们如何mock?
2.我们如何mock这个方法所在的实现类?因为该实现类是通过spring ioc 容器生成并注入的。
要回答这两个问题,我们首先需要看看,我们的测试代码:
``` @RunWith(PowerMockRunner.class) @PrepareForTest(HttpUtil.class) public class MyInvoiceServiceImplTest { @InjectMocks private MyInvoiceService myInvoiceService = new MyInvoiceServiceImpl(); @Before public void setUp(){ PowerMockito.mockStatic(HttpUtil.class); } @Test public void testGetMyInvoice() throws Exception { String result_http="{"result":[{"addDate":1509010776000,"buyerId":" + ""9E59A2D27B7748848FB65041B854240E","headName":"项伟测试"," + ""headType":"0","invoiceId":"9747A51B57FF4EA781F1CFDF73A0D9DF"," + ""invoiceType":"0","isDefault":0},{"addDate":1509092635000,"" + "buyerId":"9E59A2D27B7748848FB65041B854240E","editDate":1509094177000,"headName":"项伟测试二","headType":"0","invoiceId":"720CF6C50E594283B01C79D03D6D52B2"" + ","invoiceType":"0","isDefault":1}],"msg":"成功","code":104}"; // 1、 buyerId为空 String buyerId = null; Assert.assertEquals(null, myInvoiceService.getMyInvoice(buyerId)); // 2、buyerId不为空 buyerId = "FF8080810F5E601526"; PowerMockito.when(HttpUtil.getHttp(anyString())).thenReturn(result_http); List ``` |
第一个问题:我们通过PowerMockito.mockStatic(HttpUtil.class); 一个静态方法的实现类。然后就可以调用该静态方法。
第二个问题:@InjectMocks注解来mock我们需要测试的业务类。
至此,我们就可以通过powermock对service层的方法进行单元测试了。
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。