Solidity

用於單元測試的模擬智能合約

  • January 24, 2019

我是 Ethereum 和 solidity 的新手,我正在使用 Truffle 開發一個簡單的去中心化應用程序,其中我有一個抽象合約Storage和另一個Reader使用儲存的合約。

contract Storage {
   function getWeight() public view returns(uint8);
   function setWeight(uint8 weight) public view returns(bool); 
}

contract Reader {
   Storage private storage;
   constructor(address storageAddress) {
       storage = Storage(storageAddress);
   }
}

我正在嘗試為契約編寫單元測試Reader,是否有模擬抽象契約的行為?如果不是,那麼針對這種情況的最佳做法是什麼?

我創建了儲存合約的一個小實現。請注意,我將您的抽象重命名為 StorageInterface。

我還向 Reader 添加了一些功能,因為除非它做某事,否則沒有太多要測試的東西。因此,現在您在 Reader 中有一個 setter/getter,它轉發到作為介面實現的 Storage 合約。

看著它,我覺得我對使用“Storage”感到不舒服,因為這是一個小寫形式的保留字。我還省去了uint8看起來過早的優化。

還有一件小事。介面將 setter 聲明為view,但由於它寫入合約狀態,所以不能這樣。

pragma solidity 0.4.24;

contract StoreInterface {
   function getWeight() public view returns(uint);
   function setWeight(uint weight) public returns(bool); 
}

/**
* Just a very simple set of stubs ...
* Deploy a "Store" and then pass its address into Reader's constructor.
*/

contract Store is StoreInterface {

   uint weight;

   event LogSetWeight(address sender, uint weight);

   function getWeight() public view returns(uint) {
       return weight;
   }

   function setWeight(uint _weight) public returns(bool) {
       weight = _weight;
       emit LogSetWeight(msg.sender, _weight);
       return true;
   } 
}

contract Reader {

   StoreInterface store;

   constructor(address storeAddress) public {
       store = StoreInterface(storeAddress);
   }

   function getWeight() public view returns(uint) {
       return store.getWeight();
   }

   function setWeight(uint weight) public returns(bool) {
       return store.setWeight(weight);
   }
}

希望能幫助到你。

引用自:https://ethereum.stackexchange.com/questions/51965