简体   繁体   English

全班学习单元测试

[英]Full class coverage Unit testing

I'm currently looking into unit testing but not quite sure how full branch and class coverage can be achieved. 我目前正在研究单元测试,但不太确定如何实现完整的分支和类覆盖。

Given the following class: 给定以下类别:

public class foo
{

  public int multiply(int a, int b)
  {
      int returnVal = 0;
      if(a==0 || b == 0)
      {
         return returnVal;
      }
      if(a==1)
      {
        return b;
      }
      else if(b==1)
      {
         return a;
      }
      for(int i = 0; i < a; i++)
      {
         returnVal += b;
      }
}

What could I do to the above code to make it 100% branch coverage capable? 我如何对上述代码进行处理,以使其具有100%的分支覆盖能力?

What could I do to the above code to make it 100% branch coverage capable? 我如何对上述代码进行处理,以使其具有100%的分支覆盖能力?

If I've read your code correctly, then you don't need to change it. 如果我已正确阅读您的代码,则无需更改它。 If you want 100% coverage, you just need to design the test cases appropriately. 如果您希望100%的覆盖率,则只需要适当地设计测试用例即可

(Hint: if I've counted correctly, you can get 100% coverage with a set of 5 test cases ...) (提示:如果我计算正确,则可以通过一组5个测试用例获得100%的覆盖率...)

You can cover all your code with 5 unit tests. 您可以使用5个单元测试覆盖所有代码。

Tests 测试

when a = 0 当a = 0时

multiply(0, 13) must return 0 multiply(0, 13)必须返回0

when b = 0 当b = 0时

multiply(13, 0) must return 0 multiply(13, 0)必须返回0

when a = 1 当a = 1时

multiply(1, 13) must return 13 multiply(1, 13)必须返回13

when b = 1 当b = 1时

multiply(13, 1) must return 13 multiply(13, 1)必须返回13

nominal case 名义案例

multiply(5, 4) must return 20 multiply(5, 4)必须返回20

Tip 小费

Note that with Junit you can use parameterized tests . 请注意,使用Junit可以使用参数化测试

There are more to add as coverage criteria and not only 还有更多要添加的覆盖标准 ,而不仅仅是

full branch and class coverage 全面的分支机构和班级覆盖

will be enough. 足够了。 If we're talking about Basic coverage criteria there are a number of coverage criteria, the main ones: 如果我们谈论的是基本覆盖标准 ,则有很多覆盖标准,主要是:

  • Function coverage - Has each function (or subroutine) in the program been called? 功能介绍-程序中的每个功能(或子程序)是否都已被调用?
  • Statement coverage - Has each statement in the program been executed? 语句范围-程序中的每个语句是否都已执行?
  • Already mentioned Branch coverage - Has each branch (aka DD-path) of each control structure (such as in if and case statements) been executed? 已经提到的分支覆盖范围-是否已执行每个控制结构(例如if和case语句中)的每个分支(又称DD路径)? For example , given an if statement, have both the true and false branches been executed? 例如 ,给定一个if语句,是否同时执行了true和false分支? Another way of saying this is, has every edge in the program been executed? 换句话说,程序中的每个边都执行了吗?
  • Condition coverage (or predicate coverage) - Has each Boolean sub-expression evaluated both to true and false? 条件覆盖率(或谓词覆盖率)-每个布尔子表达式是否都评估为true和false?

If you're interested and want to read more about - code coverage criteria . 如果您有兴趣并想了解更多关于- 代码覆盖率的准则

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM