class: title # Testing Smart Contracts --- class: left ## Agenda 1. Testing Principles 2. Embark and Mocha Tests 3. Do it yourself --- ## “Testing is the primary purpose of a Smart Contract Developer” ## Very little time is spent writing code compared to the time writing tests --- ## Test Driven Development - Understand the business requirement - Created automated tests meeting said requirement - Run the test. It should fail. - Create code logic implementing the functionality - Run the test again. It should pass - Once all tests pass, the coding functionality fulfills that specific requirement - Refactor the code for future maintainability, and rerun all the tests to ensure you didn't break anything --- ## Functional: Unit Tests - Keeping units extremely small - Test every method and individual parameters at a time --- ## Good Unit Test - Runs quickly - very fast setup and breakdown time - Runs in isolation - should be reorderable and not affect the passing/failing of tests - Using mock data - making them easier to understand - Using real data - when the functionality requires - Represents a single step towards your end goal --- ## Integration Test - Testing interaction with external class or module - Used to be able to tell whether parts are working together and connected as expected --- background-image: url(bg.jpeg) ## Mistakes in Smart Contracts Mistakes in smart contracts are deadly expensive. A small mistake could cost millions. **100% code coverage is a minimum.** --- ## Achieving 100% Code Coverage - Each statement in your contract should be hit when your test suite runs - Use software & your team to determine whether or not you have a 100% coverage ### How do I achieve it? - Positive - test that your code behaves as expected with *valid* data - Negative - test that your code behaves as expected with *invalid* data --- ## Failing Tests Make sure your tests are testing what you think they are testing. If a test is supposed to fail, make sure it's failing for the right reason. --- ## I found a bug. What do I do? *TDD.* 1. Write a new test that fails if the bug is present 2. Correct the broken code 3. Run your test suite again and expect all your tests to pass 4. Commit both the code and the test suite to git - This ensures that you do not re-introduce old bugs --- ## Testing Smart Contracts ### Mocha - Tests should be organized in `contract()` suits - A single test in the suite should make use of `it()` ### Chai - Using expect or should in idiomatic languages - ie: expectation that something is going to happen --- ## Lab Use the contracts that you used for Deep Dive into Solidity. Write tests for these contracts. Ensure that you are getting 100% statement test coverage.