对于某时区的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());
    }

}

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

相关文章推荐

TimeZone_demo_时区例子

  • 2012年12月21日 10:30
  • 49KB
  • 下载

python mock 的一些小例子

1.假如我想要mock库中date对象,但是我只想mocktoda
  • gningh
  • gningh
  • 2014年09月09日 17:33
  • 2401

android mock的文档

  • 2012年10月17日 20:06
  • 356KB
  • 下载

google mock doc

  • 2014年08月05日 14:06
  • 122KB
  • 下载

Mock+Proxy在SDK项目的自动化测试实战

项目背景广告SDK项目是为应用程序APP开发人员提供移动广告平台接入的API程序集合,其形态就是一个植入宿主APP的jar包。提供的功能主要有以下几点: - 为APP请求广告内容 - 用户行为打点...
  • wpyily
  • wpyily
  • 2016年10月18日 10:47
  • 3244

SCJP Mock Exam one

  • 2008年04月14日 13:31
  • 76KB
  • 下载

spring-mock-2.0.8.jar

  • 2010年01月09日 20:01
  • 102KB
  • 下载

比较完整的junit单元测试之-----mock模拟测试

介绍   本文将介绍模拟测试框架Mockito的一些基础概念, 介绍该框架的优点,讲解应用Mockito的Java示例。 模拟(Mock)的概念    在软件开发的世界之外, "...

时区补全补丁

  • 2016年01月25日 20:41
  • 10KB
  • 下载

系统时区设置

  • 2017年08月03日 09:25
  • 531KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:对于某时区的mock的例子
举报原因:
原因补充:

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