Solidity unit testing using remix-tests -part 3

Testing scenarios example

Aniket
Remix Project

--

Note: This blog is more of a technical one. If you haven’t worked with remix-tests or not very familiar with it, you should first read part1 & part2 of this series.

As more people are looking to use remix-tests module/ Solidity Unit Testing plugin of Remix-IDE to unit test their contracts, one should know how he/she can test different cases with remix-tests using Solidity’s features. Here are some popular testing scenarios, explained with the relevant code.

In this blog, we cover cases for:

  • Testing a method working with msg.sender
  • Testing a method execution
  • Testing a method working with msg.value

Testing a method working with msg.sender

In Solidity, msg.sender plays a great role in restricting the user for certain actions. Let's take an example to test the following scenario:

Sender.sol [ Contract/Program to be tested ]

Sender_test.sol [ Test contract/program ]

See full code: https://remix-ide.readthedocs.io/en/latest/unittesting_examples.html#testing-a-method-involving-msg-sender

Testing method execution

With Solidity, one can directly verify the changes made by a method in storage by retrieving those variables from a contract. But testing for a method’s execution takes some strategy. Well that is not entirely true, when a test is successful — it is usually obvious why it passed. However, when a test fails, it is essential to understand why it failed.

To help in such cases, Solidity introduced the try-catch statement in version 0.6.0. Previously, we had to use low-level calls to track down what was going on.

Here is an example test file that use both try-catch blocks and low level calls:

AttendanceRegister.sol [ Contract/Program to be tested ]

AttendanceRegister_test.sol [ Test contract/program ]

See full code: https://remix-ide.readthedocs.io/en/latest/unittesting_examples.html#testing-method-execution

Testing a method working with msg.value

In Solidity, we can transfer ether along with a method call which is accessed inside contract as msg.value . remix-tests also provides functionality to pass value with a method call to tests its functionality.

Here is the example:

Value.sol [ Contract/Program to be tested ]

Value_test.sol [ Test contract/program ]

See full code: https://remix-ide.readthedocs.io/en/latest/unittesting_examples.html#testing-a-method-involving-msg-value

I hope these examples help you to use remix-tests module/ Solidity Unit Testing plugin of Remix-IDE more effectively.

Stay tuned to Remix IDE documentation for latest updates.

Please share your feedback/queries/suggestion to Remix gitter channel.

Thanks for reading.

--

--