Mocking是什么?

Mocking是一种在隔离测试一个类的功能。例如,无需数据库连接或属性文件中读取或文件服务器上读取需要测试的功能。 mock对象做实服务的嘲讽。一个mock对象返回对应于传递给它一些虚拟输入无效数据。

EasyMock

EasyMock便于无缝地创建模拟对象。它使用Java反射,以创造为给定接口的模拟对象。模拟对象是什么,只不过是代理的实际实现。考虑如:股票服务的情况下,它返回一个股票价格的详细信息。在开发过程中,实际的库存服务不能被用于获得实时数据。因此,我们需要一个虚拟的股票实施服务。简易模拟可以很容易理解顾名思义这样。

EasyMock的好处

  • 不用手写 -  没有必要通过自己编写的模拟对象。

  • 重构安全 - 重构接口方法的名称或重新排序的参数不会破坏测试代码在运行时创建。

  • 返回值支持 - 支持返回值。

  • 异常支持 - 支持例外/异常。

  • 命令检查支持 - 支持检查命令方法调用。

  • 注释支持 - 支持使用注解创建。

考虑下面的代码片段。

package com.yiibai.mock;import java.util.ArrayList;import java.util.List;import org.easymock.EasyMock;public class PortfolioTester {
   public static void main(String[] args){

      //Create a portfolio object which is to be tested		
      Portfolio portfolio = new Portfolio();

      //Creates a list of stocks to be added to the portfolio
      List<Stock> stocks = new ArrayList<Stock>();
      Stock googleStock = new Stock("1","Google", 10);
      Stock microsoftStock = new Stock("2","Microsoft",100);

      stocks.add(googleStock);
      stocks.add(microsoftStock);		

      //Create the mock object of stock service
      StockService stockServiceMock = EasyMock.createMock(StockService.class);

      //mock the behavior of stock service to return the value of various stocks
      EasyMock.expect(stockServiceMock.getPrice(googleStock)).andReturn(50.00);
      EasyMock.expect(stockServiceMock.getPrice(microsoftStock)).andReturn(1000.00);

      EasyMock.replay(stockServiceMock);
      //add stocks to the portfolio
      portfolio.setStocks(stocks);
      //set the stockService to the portfolio
      portfolio.setStockService(stockServiceMock);

      double marketValue = portfolio.getMarketValue();

      //verify the market value to be 10*50.00 + 100* 1000.00 = 500.00 + 100000.00 = 100500
      System.out.println("Market value of the portfolio: "+ marketValue);
   }}

让我们来了解上述程序的重要概念。完整的代码在第一个应用。

  • Portfolio  - 进行股票名单,并获得用股票价格和股票数量计算的市场价值的对象。

  • Stock  - 携带一只股票的详细信息,如它的id,名称,数量等的对象

  • StockService - 股票的服务接口,其功能是返回一个股票的当前价格。

  • EasyMock.createMock(...)  - EasyMock股票创建了服务的模拟

  • EasyMock.expect(...).andReturn(...) - 模拟实现StockService接口用getPrice方法。对于googleStock,回到50.00的价格。

  • EasyMock.replay(...) - EasyMock准备模拟对象,以便它可以被用于测试目的。

  • portfolio.setStocks(...) - 现在的投资组合包含了两只股票列表。

  • portfolio.setStockService(...) - 分配的StockService模拟对象来组合。

  • portfolio.getMarketValue() - 基于使用的模拟股票服务公司的股票投资组合回报的市场价值。


812阅读 | 0评论
你的回应
  • voxoqukuvo

    2019-09-06 16:10:06 voxoqukuvo

    The ntt.riod.osbaike.net.oia.kw rebuild [URL=http://cerisefashion.com/zoloft/]zoloft[/URL] [URL=http://solepost.com/cheap-cialis/]cialis 20[/URL] [URL=http://modreview.net/retin-a/]retin a cream[/URL] [URL=http://meetatsonoma.com/amoxicillin/]amoxicillin 500 mg[/URL] [URL=http://secretsofthearchmages.net/prilosec/]generic prilosec[/URL] [URL=http://iliannloeb.com/rosuvastatin/]rosuvastatin[/URL] rosuvastatin [URL=http://freemonthlycalender.com/inderal/]inderal canada[/URL] donation verbally captopril, zoloft for

  • eqimajuhice

    2019-09-02 22:44:04 eqimajuhice

    Insert zie.zkjs.osbaike.net.byr.ic words; [URL=http://charlotteelliottinc.com/kamagra/]kamagra[/URL] [URL=http://cgodirek.com/digoxin/]digoxin lowest price[/URL] [URL=http://ralstoncommunity.org/lasix/]lasix online[/URL] [URL=http://sallyrjohnson.com/buy-prednisone/]prednisone[/URL] [URL=http://telugustoday.com/benemid/]buy benemid[/URL] [URL=http://myquickrecipes.com/viagra/]price of 100mg viagra[/URL] [URL=http://cgodirek.com/aciphex/]aciphex lowest price[/URL] secondary, reheat k

  • eqolfou

    2019-08-26 13:57:32 eqolfou

    Most mwp.xxcq.osbaike.net.idc.mc elastic, step, [URL=http://wellnowuc.com/lasix/]lasix online[/URL] [URL=http://solepost.com/cialis-20-mg-price/]lowest price for cialis 20 mg[/URL] [URL=http://sbmitsu.com/penegra/]penegra without dr prescription[/URL] [URL=http://vintagepowderpuff.com/cialis/]cialis 10mg[/URL] [URL=http://rockymountainmbaa.com/cialis-com/]cialis.com lowest price[/URL] [URL=http://passagesinthevoid.com/xalatan/]online xalatan[/URL] [URL=http://puresportsnetwork.com/buy-propecia-online/]propecia[/URL] albumin radicals, protruded

  • SuperSlotsswedy

    2019-08-25 01:58:22 SuperSlotsswedy

    Доброго времени суток! Не упустите момент получить самые "новые предложения" проекта игорного заведения Casino-X! [b]Казино онлайн Casino-X доступен на любом языке[/b] и для самых актуальных стран! [b]Азартный клуб - зеркало Casino-X - [/b][url=https://cosino-x.xyz/][b]Бесплатный сувенир ради регу[/b][/url] [b]Пример игры - можно играть сразу на этом сайте без регистрации и бесплатно - ЖМИ НА КАРТИНКУ ИГРЫ[/b] Рекомендую [URL=https://zdes-kino.ru/]фильмы хорошего каче

  • owiwaci

    2019-08-11 15:43:17 owiwaci

    Emergency nnw.axxb.osbaike.net.txd.mb inadvertent [URL=http://discoveryshows.com/cialis-soft/]buy cialis soft[/URL] cialis soft lowest price [URL=http://gaiaenergysystems.com/dapoxetine/]priligy[/URL] [URL=http://discoveryshows.com/viagra-soft/]viagra soft online[/URL] [URL=http://elegantearthatthearbor.com/valtrex-online/]valtrex neck ache[/URL] [URL=http://vintagepowderpuff.com/viagra-online/]buy viagra online[/URL] viagra for sale [URL=http://davincipictures.com/kamagra/]buy kamagra online[/URL] [URL=http://earthbeours.com/cialis-canadian-pharmacy/]generic cialis canadian pharmacy[/URL] [URL=http://davincipictures.com/viagra-buy-in-canada/]cheep viagra[/URL] enhancing warm, cialis soft lowest price priligy dapoxetine order viagra soft online valtrex online viagra cheap kamagra buy cialis online canada pharmacy generic viagra 50 mg hidden http://discoveryshows.com/cialis-soft/ cialis soft http://gaiaenergysystems.com/dapoxetine/ dapoxetine online http://discoveryshows.com/viagra-soft/ viagra soft online http://elegantearthatthearbor.com/valtrex-online/ valtrex online valtrex online http://vintagepowderpuff.com/viagra-online/ viagra for sale http://davincipictures.com/kamagra/ kamagra http://earthbeours.com/cialis-canadian-pharmacy/ on line pharmacy http://davincipictures.com/viagra-buy-in-canada/ v

  • abmirecafiuma

    2019-08-03 22:57:41 abmirecafiuma

    The ifl.rsjk.osbaike.net.hgg.gj oesophagectomy; periosteal [URL=http://washingtonsharedparenting.com/lisinopril/]personal injury lisinopril[/URL] [URL=http://jacksfarmradio.com/ventolin-inhaler-for-sale/]ventolin inhaler[/URL] [URL=http://buckeyejeeps.com/super-kamagra/]super kamagra generic[/URL] [URL=http://bikramcentennial.com/indocin/]indocin colchicine[/URL] [URL=http://puresportsnetwork.com/pharmacy/]pharmacy[/URL] [URL=http://mrcpromotions.com/rulide/]online rulide[/URL] [URL=http://fitnesscabbage.com/cialis-com-lowest-price/]cialis tadalafil 20 mg ta

  • ukudalvuwope

    2019-07-23 21:40:42 ukudalvuwope

    Other qjb.qdng.osbaike.net.avb.yh space-occupying [URL=http://timoc.org/viagra-online/]viagra.com[/URL] [URL=http://nicaragua-magazine.com/viagra-100mg/]viagra canada[/URL] [URL=http://nicaragua-magazine.com/viagra/]viagra[/URL] [URL=http://timoc.org/prednisone-20-mg/]prednisone[/URL] [URL=http://earthbeours.com/viagra-generic/]viagra[/URL] [URL=http://nicaragua-magazine.com/viagra-online/]viagra 100mg price walmart[/URL] [URL=http://dead-fish.com/buy-cialis/]cialis online[/URL] [URL=http://thebestworkoutplan.com/tadalafil-20-mg/]buy tadalafil online[/URL] cialis generic 20 mg [URL=http://nicaragua-magazine.com/cialis-20-mg/]cialis.com[/URL] irrespective viagra for sale viagra canada cheap viagra deltasone and pregnancy category cheap viagra pills canadian viagra cialis prezzo farmacia cialis lowest price for cialis 20 mg cialis 20 mg fasciculus non-pregnant parasite http://timoc.org/viagra-online/ viagra generic paypal http://nicaragua-magazine.com/viagra-100mg/ viagra on line http://nicaragua-magazine.com/viagra/ buy viagra online http://timoc.org/prednisone-20-mg/ prednisone 10 mg http://earthbeours.com/viagra-generic/ online viagra http://nicaragua-magazine.com/viagra-online/ viagra online http://dead-fish.com/buy-cialis/ cialis from canada http://t

  • enuuxadled

    2019-07-12 08:47:21 enuuxadled

    It xpu.gfhw.osbaike.net.bev.ov conducting [URL=http://heavenlyhappyhour.com/fluoxetine/]fluoxetine lowest price[/URL] [URL=http://quotes786.com/vidalista/]potenzmittel ginerika vidalista[/URL] [URL=http://iowansforsafeaccess.org/tadalafil-20-mg/]cialis 20 mg[/URL] [URL=http://disclosenews.com/revia/]price of revia[/URL] [URL=http://heavenlyhappyhour.com/vidalista/]vidalista[/URL] [URL=http://bootstrapplusplus.com/cialis-5mg/]cialis 10mg[/URL] [URL=http://thefashionhob.com/cheap-cialis/]cialis[/URL] [URL=http://quotes786.com/cialis-professi

  • iminasayatxi

    2019-06-29 21:17:11 iminasayatxi

    Some fio.aarx.osbaike.net.dmz.xg dread overhearing tarso-metatarsal [URL=http://quotes786.com/cialis-professional/]cialis professional without dr prescription[/URL] [URL=http://dive-courses-bali.com/prednisone/]buy prednisone online in us[/URL] [URL=http://thefashionhob.com/cialis-20-mg-price/]how many mg does cialis come in[/URL] [URL=http://livetvchannels.org/viagra-super-active/]viagra super active[/URL] [URL=http://tattoosideasblog.com/cialis-online/]cialis online[/URL] [URL=http://quotes786.com/eriacta-for-sale/]eriacta[/URL] [URL=http://heavenlyhappyhour.com%

  • uqeboxaloquc

    2019-06-26 22:34:04 uqeboxaloquc

    To oah.msli.osbaike.net.nmq.pe whooping [URL=http://quotes786.com/vidalista/]discount vidalista[/URL] [URL=http://heavenlyhappyhour.com/vidalista/]vidalista 20 recensioni[/URL] [URL=http://bootstrapplusplus.com/lasix/]lasix[/URL] [URL=http://solartechnicians.net/lyrica/]lyrica[/URL] [URL=http://alwaseetgulf.com/tadalafil-20-mg/]cialis[/URL] headedness, lower-third tamponade vidalista vidalista without a prescription

1 2345
联系我们