___
# **Test Coverage**
___
---
#### What is test coverage?
*test coverage is a **measure** used to describe the degree to which the source code of a program is executed when a particular test suite runs.*
*In other words - Test Coverage - is **the number of lines of code in the software being tested**.*
---
#### *e.g*
*If the total lines of code in a system component is 1000 and the number of lines being actually executed through all existing test cases is 650, then your test coverage is:*
> `(650 / 1000) * 100 = 65%`
---
#### Why is test coverage useful?
- *Test coverage helps improve your chances of catching all the critical/high priority bugs.*
- *To find the areas in specified requirement which is not covered by the test scenarios and cases.*
- *The check on quality of the application.*
---
#### What is nyc? how is it related to test coverage?
*"nyc" is a package of "istanbul". And it used to get the **test coverge**.*
*To use nyc we need to update the "package.json" by installing a package manager to add it as a dev dependency using*
> sudo npm install -D nyc -g
---
*When we use nyc we call npm scripts and insert it to scripts block*
```
{
"scripts": {
"test": "mocha",
"coverage": "nyc npm run test"
}
}
```
*run using terminal*
> nyc npm run test
---
*nyc generated how much line percentage has been covered for example:*

---
*prefer the icov-report:
shortcut to running this command:*
> nyc report –reporter =icov --reporter=text
---

---
### Does 100% coverage mean you have tested everything correctly?
---
*Well NO! Because even if all your classes have 100% coverage, that still doesn’t mean they will correctly interact with each other.*
---
for example:
```
public class Calculator {
public int sum(int a, int b) {
return a+b;
}
}
```
*here we can see that the code coverage is 100%.
are you sure every thing will work as expected for that class?*
*NO* :stuck_out_tongue:
---
*This is because code coverage doesn’t tell you anything about the quality of your tests. It only counts what lines of code are executed during tests and what aren’t.*
---
A good Calculator test (with 100% line coverage) would be:
```
@Test
public void sumOfOneAndThreeShouldBeFour() throws Exception {
int result = new Calculator().sum(1,3);
assertEquals(4, result)
}
```
---
```
public class Calculator {
public int sum(int a, int b) {
return 4;
}
}
```
All above tests would still pass, code coverage would be 100% but your code doesn’t functionally do what it should. We would need to add multiple tests (covering the same line of code) to guarantee that.
---
Code coverage != quality of tests
So coverage doesn’t ensure your tests:
- do an actual assert
- are complete (cover all functionality)
---
Thank You for listening :ear:
{"metaMigratedAt":"2023-06-14T22:51:06.956Z","metaMigratedFrom":"Content","title":"**Test Coverage**","breaks":true,"contributors":"[{\"id\":\"c812783e-2740-47d0-8981-33bca2701792\",\"add\":4851,\"del\":1932}]"}