【发布时间】:2015-02-10 21:49:28
【问题描述】:
我正在尝试编写一个 Junit 来测试具有当前时间戳的对象。问题是当我第一次创建当前时间戳时,如下所示:
Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
它创建一个时间戳对象,其当前时间包括毫秒。所以当我运行我的测试时,它们永远不会相等,因为在我创建时间戳对象和测试时间之间有一段时间以毫秒为单位:
x.setTimeToMyMethod(timestamp);
assertEquals(timestamp, x.getTimeFromMyMethod());
我尝试使用 SimpleDateFormat,但它将时间转换为字符串,而我的 setter 方法只接受 Timestamp 对象。 无论如何我可以克服这个问题吗? 提前致谢!
感谢您的回答,这是我的代码,希望它能阐明我想要做什么:
public class myTest {
Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
myTestingClass testClass = new myTestingClass();
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
testClass.setCreateDate(timestamp);
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
try {
assertEquals(timestamp, testClass.getCreateDate());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
当我尝试运行它时,它给了我以下错误:
java.lang.AssertionError:预期: 但是 是:
【问题讨论】:
-
你能解释一下第二个
Timestamp对象是在哪里创建的吗?在您的(简短)示例代码中,不清楚问题是在哪里引起的。 -
@Duncan 我编辑了我的问题,感谢您的评论!