我一直在调试一些现有代码,这些代码在我的系统上单元测试失败,但在同事的系统上没有。根本原因是 SimpleDateFormat 在解析应该可解析的日期时抛出 ParseExceptions。我创建了一个单元测试来演示在我的系统上失败的代码:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import junit.framework.TestCase;
public class FormatsTest extends TestCase {
public void testParse() throws ParseException {
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss.SSS Z");
formatter.setTimeZone(TimeZone.getDefault());
formatter.setLenient(false);
formatter.parse(formatter.format(new Date()));
}
}
此测试在我的系统上引发 ParseException,但在其他系统上成功运行。
java.text.ParseException: Unparseable date: "20100603100243.118 -0600"
at java.text.DateFormat.parse(DateFormat.java:352)
at FormatsTest.testParse(FormatsTest.java:16)
我发现我可以setLenient(true)
并且测试会成功。这setLenient(false)
是该测试模仿的生产代码中使用的内容,因此我不想更改它。