简体   繁体   English

使用Java更改系统时间

[英]Change System time using Java

I have a situation where I need to change the system time programatically using Java. 我遇到一种情况,需要使用Java以编程方式更改系统时间。 Is there any way to do it with Java or Selenium? 使用Java或Selenium有什么办法吗?

No , Selenium is API to talk with browsers only so you cant achieve this using Selenium. ,Selenium是浏览器通信的 API,因此您无法使用Selenium实现此目的。
Even Java doesn't provide any API for this: How can I set the System Time in Java? 甚至Java也没有为此提供任何API: 如何在Java中设置系统时间?

Why exactly do you need to modify the system time? 为什么需要修改系统时间呢? I can only think it's because you want to validate the display of a date on a page. 我只能认为这是因为您要验证页面上日期的显示。 If this is the case, I would recommend taking 'test_start_time' and 'test_end_time' datestamps, and validating the value you receive from selenium as being within these limits rather than asserting a specific time. 如果是这种情况,我建议您使用“ test_start_time”和“ test_end_time”日期戳,并验证您从硒中获得的值在这些限制之内,而不是断言特定的时间。

If you need it for another reason then there are options, but they're pretty hacky. 如果您出于其他原因需要它,那么可以选择,但是它们很笨拙。 :( :(

  1. If you know that the date is being retrieved in javascript, you can trying redefining the date object to return the date you want instead of the system date/time. 如果您知道正在使用javascript检索日期,则可以尝试重新定义日期对象以返回所需的日期,而不是系统日期/时间。 You'll need to insert a selenium script doing something like this: Javascript - overriding new Date() behavior to offset GMT . 您需要插入一个执行以下操作的Selenium脚本: Javascript覆盖新的Date()行为以抵消GMT I really wouldn't recommend this, but's it's definitely a lot cleaner than option 2. 我确实不推荐这样做,但是绝对比选择2干净得多。
  2. If your date is being generated on the back end and you have access to the back end code, you could add a layer of indirection to all relevant date references which by default returns the date as normal. 如果您的日期是在后端生成的,并且您可以访问后端代码,则可以在所有相关的日期引用中添加一个间接层,默认情况下,该日期默认将正常返回该日期。 Then, when starting your server for a test run, you could mock out the returned date as required (perhaps using an API to set you requirements). 然后,在启动服务器进行测试运行时,您可以根据需要模拟返回的日期(也许使用API​​来设置您的要求)。 It makes me a bit ill just thinking about it though, and I really wouldn't recommend doing this. 但是,仅考虑它会让我有点不适,我真的不建议这样做。
  3. If you think you need to modify system time to fit some imported test data, you should look into generating this data for each test, or even templating existing data using something like http://velocity.apache.org/ to set the date at run time (prior to import). 如果您认为需要修改系统时间以适合某些导入的测试数据,则应考虑为每个测试生成此数据,甚至可以使用http://velocity.apache.org/等将现有数据作为模板来设置日期为运行时间(导入之前)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM