对于某时区的mock的例子

原创 2016年08月29日 10:11:10

这是针对基于timezone的程序的例子写的单元测试,里面用到了mock

//需要被测试的对象之一 DatetimeEnricher.java
public class SFDatetimeEnricher implements SFEnricher {

    final private DateService dateService;

    public SFDatetimeEnricher(DateService dateService) {
        this.dateService = dateService;
    }

    @Override
    public void enrich(AllocationSnapshotEvent allocationSnapshotEvent, AllocationLegSnapshot allocationLegSnapshot, SFTradeEvent targetTradeEvent) {
        setTGPublishTime(targetTradeEvent);
        setTradeDate(targetTradeEvent);
        setTransactionTime(targetTradeEvent);
        setEnteredTime(targetTradeEvent);
        setFinancialDate(targetTradeEvent);
    }

    private void setEnteredTime(SFTradeEvent targetTradeEvent) {
        targetTradeEvent.setEnteredTime(dateService.now());
    }

    private void setTransactionTime(SFTradeEvent targetTradeEvent) {
        targetTradeEvent.setTransactionTime(dateService.now());
    }

    private void setTradeDate(SFTradeEvent targetTradeEvent) {
        ((TradeEventContainer)targetTradeEvent).putHeaderField(TradeHeaderKey.TradeDate,dateService.today(targetTradeEvent.getPOGroup()));
    }

    public void setTGPublishTime(SFTradeEvent targetTradeEvent) {
        targetTradeEvent.setTGPublishTime(dateService.now());
    }

    public void setFinancialDate(SFTradeEvent targetTradeEvent) {
        for (SFTradeLeg leg : targetTradeEvent.getLegs()) {
            ((TradeLeg)leg).putField(TradeLegKey.FinancialDate,(dateService.getFinancialDate(targetTradeEvent.getPOGroup())));
        }
    }

}
//需要被测试的第2个对象  DateService
public class JodaDateService implements DateService {

    private Map<String, String> timeZoneMapping = ImmutableMap.of("LOH", "Europe/London", "HKH", "Asia/Hong_Kong", "NYH", "America/New_York");
    private Map<String, String> cutTimeMapping = ImmutableMap.of("LOH", "23:59", "HKH", "17:00", "NYH", "22:00");
    private final Map<String, Integer> cutOFFTimeValueMapping = new HashMap<>();

    private static final ThreadLocal<SimpleDateFormat> dateFormatter = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    public JodaDateService() {
        this.initutOfffTimeValueMapping();
    }

    public void initutOfffTimeValueMapping() {
        for (Map.Entry<String, String> entry : cutTimeMapping.entrySet()) {
            String rawCutOffTime = this.cutTimeMapping.get(entry.getKey());
            int cutoffHour = Integer.parseInt(rawCutOffTime.split(":")[0]);
            int cutoffMinute = Integer.parseInt(rawCutOffTime.split(":")[1]);
            int totalCutOffSeconds = cutoffHour * 3600 + cutoffMinute * 60;
            cutOFFTimeValueMapping.put(entry.getKey(), totalCutOffSeconds);
        }
    }

    @Override
    public Date now() {
        return DateTime.now().toDate();
    }

    @Override
    public String today(String POGroup) {
        DateTimeZone dateTimeZone = DateTimeZone.forID(this.timeZoneMapping.get(POGroup));
        DateTime dateWithZone = new DateTime(dateTimeZone);
        Date date = dateWithZone.toLocalDateTime().toDate();
        return dateFormatter.get().format(date);
    }

    @Override
    public String getFinancialDate(String POGroup) {
        DateTime currentDateTime = new DateTime().withZone(DateTimeZone.forID(this.timeZoneMapping.get(POGroup)));
        int currentHour = currentDateTime.getHourOfDay();
        int currentMinute = currentDateTime.getMinuteOfHour();
        int totalCurrentSeconds = currentHour * 3600 + currentMinute * 60 + currentDateTime.getSecondOfMinute();
        Date result;
        if (totalCurrentSeconds <= this.cutOFFTimeValueMapping.get(POGroup)) {
            result = currentDateTime.toLocalDateTime().toDate();
        } else {
            result = currentDateTime.plusDays(1).toLocalDateTime().toDate();
        }
        return dateFormatter.get().format(result);
    }

}

这里是单元测试的2个文件

  • 需要注意就是调用了DaTime withzoneinfo来设置时区信息,最后使用tolocaldatetimel来转换为你需要的时间
  • 另外就是这里系统最后使用的是GMT时间
public class SFDatetimeEnricherTest {

    @Before
    public void setUp() throws Exception {
        initMocks(this);
    }

    @Test
    public void enrichCanWorkWithNoErrorIn() throws Exception {
        SFTradeEvent sfTradeEvent = createAnEmptySF();
        sfTradeEvent.setPOGroup("LOH");
        LocalDateTime myDateTime = new DateTime(2016, 8, 22, 11, 18, 0, 966).toLocalDateTime();
        DateService dateService = mock(JodaDateService.class);
        when(dateService.now()).thenReturn(myDateTime.toDate());
        when(dateService.today("LOH")).thenReturn("2016-08-22");
        when(dateService.getFinancialDate("LOH")).thenReturn("2016-08-22");
        SFDatetimeEnricher datetimeEnricher = new SFDatetimeEnricher(dateService);
        datetimeEnricher.enrich(mock(AllocationSnapshotEvent.class), mock(AllocationLegSnapshot.class), sfTradeEvent);
        assertThat(sfTradeEvent.getTGPublishTime().getTime(), is(myDateTime.toDate().getTime()));
        assertThat(sfTradeEvent.getTradeDate(), is(dateConveter("2016-08-22 00:00:00")));
        assertThat(sfTradeEvent.getTransactionTime().getTime(), is(new DateTime(2016, 8, 22, 11, 18, 0, 0).toLocalDateTime().toDate().getTime()));
        assertThat(sfTradeEvent.getEnteredTime().getTime(), is(myDateTime.toDate().getTime()));
        for (SFTradeLeg leg : sfTradeEvent.getLegs()) {
            assertThat(leg.getFinancialDate().getTime(), is(dateConveter("2016-08-22 00:00:00").getTime()));
        }
    }

    private SFTradeEvent createAnEmptySF() {
        SFTradeEvent tradeEvent = SFFactory.createTradeEvent();
        SFTradeLeg leg = SFFactory.createLeg();
        tradeEvent.addTradeLeg(leg);
        return tradeEvent;
    }

    private Date dateConveter(String dateString) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date result = null;
        try {
            result = formatter.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

}
public class JodaDateServiceTest {

    @Before
    public void setUp() throws Exception {
        for (Map.Entry<String, String> entry : this.cutTimeMapping.entrySet()) {
            String key = entry.getKey();
            String rawCutOffTime = this.cutTimeMapping.get(key);
            int cutoffHour = Integer.parseInt(rawCutOffTime.split(":")[0]);
            int cutoffMinute = Integer.parseInt(rawCutOffTime.split(":")[1]);
            int totalCutOffSeconds = cutoffHour * 3600 + cutoffMinute * 60;
            this.cutOffTimeValueMapping.put(key, totalCutOffSeconds);
        }
    }

    private Map<String, String> timeZoneMapping = ImmutableMap.of("LOH", "Europe/London", "HKH", "Asia/Hong_Kong", "NYH", "America/New_York");
    private Map<String, String> cutTimeMapping = ImmutableMap.of("LOH", "23:59", "HKH", "17:00", "NYH", "22:00");
    private final Map<String, Integer> cutOffTimeValueMapping = new HashMap<>();

    @Test
    public void canGetRightDateinLOHTime() throws Exception {
        DateService dateService = new JodaDateService();
        DateTime currentDateTime = new DateTime().withZone(DateTimeZone.forID(this.timeZoneMapping.get("LOH")));
        assertThat(dateService.today("LOH"), is(dateFormatter(currentDateTime)));
        assertThat(dateService.getFinancialDate("LOH"), is(getIfNextFinancialDate("LOH")));

    }


    @Test
    public void canGetRightDateinHKHTime() throws Exception {
        DateService dateService = new JodaDateService();
        DateTime currentDateTime = new DateTime().withZone(DateTimeZone.forID(this.timeZoneMapping.get("HKH")));
        assertThat(dateService.today("HKH"), is(dateFormatter(currentDateTime)));
        assertThat(dateService.getFinancialDate("HKH"), is(getIfNextFinancialDate("HKH")));

    }


    @Test
    public void canGetRightDateinNYHTime() throws Exception {
        DateService dateService = new JodaDateService();
        DateTime currentDateTime = new DateTime().withZone(DateTimeZone.forID(this.timeZoneMapping.get("NYH")));
        assertThat(dateService.today("NYH"), is(dateFormatter(currentDateTime)));
        assertThat(dateService.getFinancialDate("NYH"), is(getIfNextFinancialDate("NYH")));

    }


    private String dateFormatter(DateTime currentDate) {
        DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
        return fmt.print(currentDate);
    }

    private String getIfNextFinancialDate(String POGroup) {

        DateTime currentDateTime = new DateTime().withZone(DateTimeZone.forID(this.timeZoneMapping.get(POGroup)));
        int currentHour = currentDateTime.getHourOfDay();
        int currentMinute = currentDateTime.getMinuteOfHour();
        int totalCurrentSeconds = currentHour * 3600 + currentMinute * 60 + currentDateTime.getSecondOfMinute();
        DateTime result;
        if (totalCurrentSeconds <= this.cutOffTimeValueMapping.get(POGroup)) {
            result = currentDateTime;
        } else {
            result = currentDateTime.plusDays(1);
        }
        return this.dateFormatter(result.toLocalDateTime().toDateTime());
    }

}

版权声明:本文为自由の力原创文章,未经允许不得转载。

一个简单的mock例子

package com.my.serviceImpl; import org.easymock.EasyMock; import org.testng.Assert; import org.test...
  • hdyrz
  • hdyrz
  • 2017年08月02日 15:32
  • 107

一个简单的cmock例子

好久以前就想试用一下cmock,但一直没有做,汗。。。 今天想起来,赶紧试一下。 在官网上,下载安装包cmock_2_0_204.zip,方便的是,不需要编译和安装。不过cmock依赖于r...
  • gohome520
  • gohome520
  • 2012年06月30日 00:39
  • 3929

mock 例子

mock: 1. for system. TEST(CCareaTest, CCareaTest_system_failed) {     int rc= 0;     char execute_fi...
  • surpass1026
  • surpass1026
  • 2012年11月20日 22:57
  • 2236

对于mock的理解

对于mock的随机数又有了新的理解。开始一直认为mock产生的随机数无法控制。其实只要在信息后面加入随机数,产生id的部分,也可以用id自增,保证id的唯一性就可以了。mock有很多方便的地方,比如可...
  • qq_24122593
  • qq_24122593
  • 2017年01月16日 17:29
  • 306

Google Mock(Gmock)简单使用和源码分析——简单使用

本文我们讲解Gmock的使用和相关实现的原理。
  • breaksoftware
  • breaksoftware
  • 2016年05月18日 18:36
  • 3372

关于软件测试中的单元测试-----mock讲解

今天下午接到百度作业帮的面试邀请电话,说要进行面试,我们约的是明天,挂了电话我上网查了一下我申请的职位竟然是软件测试,,,,好吧,只能恶补了 关于软件测试中的单元测试-----mock讲解:“ ...
  • sinat_26935081
  • sinat_26935081
  • 2015年11月05日 22:32
  • 924

JUnit与Mockito单元测试典型示例

单元测试的重要性无需赘述,但单元测试也会遇到困难,其中之一就是如何 创建依赖。试想我们常见的server端分层架构,数据访问层Dao,业务层, 以及Web层,想要单元测试业务层,我们需要依赖Dao...
  • kimylrong
  • kimylrong
  • 2016年03月31日 14:50
  • 3449

简单示例mock的使用 (Junit结合Jmock)

测试数据库时非常脆弱:数据的改变可能会影响测试的结果。  为目标的依赖创建桩(stub)或mock类是更好的解决方案。  可以使用jMock开源库来快速、简单的定义mock对象。(详细请查看:ht...
  • partner4java
  • partner4java
  • 2011年11月28日 13:48
  • 4536

使用easymock简单举例

//使用easymock模拟 类B 来测试 类 A;package test2;public class A{ BInterface b; public A(BInterface b){  this....
  • stone_star
  • stone_star
  • 2006年09月29日 23:37
  • 1086

模拟服务器MockServer之Moco详细介绍

前面一篇介绍了如何用mockito来测试我们的一些异步任务,例如网络请求时候的异步回调。  现在做进一步的介绍,一个模拟我们的服务器的东东–moco 先运行起来 请先下载这个文件moco...
  • vite_s
  • vite_s
  • 2017年01月17日 15:05
  • 1921
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:对于某时区的mock的例子
举报原因:
原因补充:

(最多只允许输入30个字)