尝试获取时间戳时出现“无法借用全局资源”错误

问题描述 投票:0回答:1

我在为模块编写单元测试时遇到问题,我意识到我无法在单元测试中获取时间戳。我尝试在下面的代码中获取时间戳,

 #[test]
    fun get_seconds() {
        timestamp::now_seconds();
    }

导致了这个错误

**$ sudo aptos move test --package-dir sources **
INCLUDING DEPENDENCY AptosFramework
INCLUDING DEPENDENCY AptosStdlib
INCLUDING DEPENDENCY MoveStdlib
BUILDING brkt
Running Move unit tests
[ FAIL    ] 0x7a3b3a0d212571b010a28b61d8cc5ff002faf4c617dfdd4f5187e10f8714d006::competition::get_seconds

Test failures:

Failures in 0x7a3b3a0d212571b010a28b61d8cc5ff002faf4c617dfdd4f5187e10f8714d006::competition:

┌── get_seconds ──────
│ error[E11001]: test failure
│    ┌─ /root/.move/https___github_com_aptos-labs_aptos-core_git_mainnet/aptos-move/framework/aptos-framework/sources/timestamp.move:62:9
│    │
│ 61 │     public fun now_microseconds(): u64 acquires CurrentTimeMicroseconds {
│    │                ---------------- In this function in 0x1::timestamp
│ 62 │         borrow_global<CurrentTimeMicroseconds>(@aptos_framework).microseconds
│    │         ^^^^^^^^^^^^^ Test was not expected to error, but it gave a MISSING_DATA (code 4008) error with error message: "Failed to borrow global resource from 0000000000000000000000000000000000000000000000000000000000000001". Error originating in the module 0000000000000000000000000000000000000000000000000000000000000001::timestamp rooted here
│ 
│ 
│ stack trace
│   timestamp::now_seconds(/root/.move/https___github_com_aptos-labs_aptos-core_git_mainnet/aptos-move/framework/aptos-framework/sources/timestamp.move:68)
│   competition::get_seconds(sources/base/competition.move:649)
│ 
└──────────────────

Test result: FAILED. Total tests: 1; passed: 0; failed: 1
{
  "Error": "Move unit tests failed"
}

有谁知道这个错误,或者我真的无法在单元测试中获取时间戳?

blockchain move aptos
1个回答
0
投票

测试使用与运行时不同的时间实例。你应该使用这样的东西:

clock::create_for_testing(ctx);

test.take_shared<Clock>();
© www.soinside.com 2019 - 2024. All rights reserved.