我有一个实例化并调用另一个合同的包装器合同,我的测试用例说所有者(msg.sender)不匹配。为什么呢?
合同A
pragma solidity ^0.4.4;
contract A {
address public owner;
function A() {
owner = msg.sender;
}
function createB(string name) {
return new B(msg.sender, name);
}
}
合同B
pragma solidity ^0.4.4;
contract B {
address public owner;
string public name;
function B(address _owner, string _name) {
owner = _owner;
name = _name;
}
}
测试用例
pragma solidity ^0.4.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/B.sol";
contract TestB {
B testB;
A testA;
function beforeEach() {
A = A(DeployedAddresses.A());
B = testA.createB("test");
}
function testOwnerIsSet() {
Assert.equal(address(A), address(B), "Owner's address does not match");
}
}
测试结果
1) TestB testOwnerIsSet:
Error: Owner's address does not match
at /Users/xxx/.config/yarn/global/node_modules/truffle/build/cli.bundled.js:214233:17
at Array.forEach (native)
at processResult (/Users/xxx/.config/yarn/global/node_modules/truffle/build/cli.bundled.js:214231:19)
at process._tickCallback (internal/process/next_tick.js:109:7)
修改
我已将address public owner
添加到contract A
。并在owner
中公开contract B
。
现在我的TestB合同看起来像这样:
pragma solidity ^0.4.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/B.sol";
contract TestB {
B testB;
A testA;
function beforeEach() {
A = A(DeployedAddresses.A());
B = testA.createB("test");
}
function testOwnerIsSet() {
address aOwner = A.owner();
address bOwner = B.owner();
Assert.equal(aOwner, bOwner, "Owner's address does not match");
}
}
答案 0 :(得分:0)
根据你所展示的内容我假设你正在使用松露?说实话,我很惊讶这会编译。
致电时,
B = testA.createB("test");
你是从TestB
打来的。 msg.sender
将是TestB
的地址。
function createB(string name) {
return new B(msg.sender, name); // msg.sender = TestB instance address
}
This可能有助于实现您的目标。