如何使用JMockit模拟Date类的默认构造函数? [英] How to mock the default constructor of the Date class with JMockit?

查看:71
本文介绍了如何使用JMockit模拟Date类的默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想模拟 java.util.date 的默认构造函数,因此它不会构造 Date 对象代表创建时间,但始终是相同的 Date 对象(在我的示例中,2010年12月31日以下).我尝试使用 JMockit JUnit 进行此操作,但是在下面执行我的测试时,输出始终为 Thu Jan 01 01:00:00 CET 1970 .那么我的 Date()模拟结果出了什么问题?

I want to mock the default constructor of java.util.date so it does not construct a Date object representing the time when it was created, but always the same Date object (in my example below 31 Dec 2010). I tried doing this with JMockit and JUnit, but when executing my test below, the output is always Thu Jan 01 01:00:00 CET 1970. So what is wrong with my mock of Date()?

import java.util.Date;

import org.junit.*;
import mockit.*;

public class AppTest {

    @Before
    public void setUp() {
        Mockit.setUpMocks(MockedDate.class);
    }

    @After
    public void tearDown() {
        Mockit.tearDownMocks();
    }  

   @Test
    public void testDate() {
        Date today=new Date();
        System.out.println(today.toString());
    }

    @MockClass(realClass=Date.class)
    public static class MockedDate {

        @Mock
        public void $init() {
            // Now should be always 31.12.2010!
            new Date(110,11,31);  //110 = 2010! 11 = December! This is sick!
        }
    }
}

推荐答案

al nik的回答对我来说是一个很好的提示.最好模拟 System 类,而不是 Date 类,以产生假时间.最后,我自己的解决方案只是模拟 System.currentTimeMillis()方法(此方法在内部由 Date()调用).

al nik's answer was a good hint for me. It is better to mock the System class instead of the Date class to generate a fake time. My own solution in the end was simply to mock the System.currentTimeMillis() method (this method is called by Date() internally).

JMockit 1.5及更高版本

new MockUp<System>(){

    @Mock
    public long currentTimeMillis() {

        // Now is always 11/11/2011
        Date fake = new Date(111,10,11);
        return fake.getTime();
    }
};

JMockit 1.4及更低版本

@MockClass(realClass = System.class)
public static class MockedSystem {

    @Mock
    public long currentTimeMillis() {

        // Now is always 11/11/2011
        Date fake = new Date(111,10,11);
        return fake.getTime();
    }
}

这篇关于如何使用JMockit模拟Date类的默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆