对于某时区的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的例子

这是针对基于timezone的程序的例子写的单元测试,里面用到了mock//需要被测试的对象之一 DatetimeEnricher.java public class SFDatetimeEnrich...

关于SQLite与SQLServer的区别

一、常见问题汇总   1 TOP   这是一个大家经常问到的问题,例如在SQLSERVER中可以使用如下语句来取得记录集中的前十条记录:   [pre] SELECT TOP 10 * F...

精选:深入理解 Docker 内部原理及网络配置

网络绝对是任何系统的核心,对于容器而言也是如此。Docker 作为目前最火的轻量级容器技术,有很多令人称道的功能,如 Docker 的镜像管理。然而,Docker的网络一直以来都比较薄弱,所以我们有必要深入了解Docker的网络知识,以满足更高的网络需求。

time函数的用法

计算今天是星期几,计算时间差 1997年7月1日 到 今天过去了多少天? #include #include //关于获取当前时间的函数 int main() { /...

高斯日记

题目标题: 高斯日记     大数学家高斯有个好习惯:无论如何都要记日记。     他的日记有个与众不同的地方,他从不注明年月日,而是用一个整数代替,比如:4210   ...

python mock 的一些小例子

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

getResource的用法对于class和classloader

最近开始接触Java web项目,选择的服务器是tomcat。 获取资源文件(利用getResource方法进行总结) package com.temp; public class TestGe...

Spring定时器,cronExpression表达式解释

字段 允许值 运行的特殊字符 秒 0-59 , - * / 分 0-59 , - * / 小时 0-23 , - * / 日期 1-31 , - ...

位于包中的servlet的部署

session与Cookie的区别;servlet的部署

Mock与Stub的区别

Mock: 关注行为验证。细粒度的测试,即代码的逻辑,多数情况下用于单元测试。 何时使用Mock: 真实对象的行为具有不确定性。真实对象难以创建。真实对象的行为难以模拟(例如网络错误...

Spring+SpringMVC+Hiberate+MySql+Bootstrap实现一个简单验证登录实例

本例子结合Spring+SpringMVC+Hiberate+MySql+Bootstrap实现一个简单验证登录实例 1工程目录: web.xml配置文件: web-app xmlns...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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