其他分享
首页 > 其他分享> > 【Springboot学习】在Springboot中进行Junit测试

【Springboot学习】在Springboot中进行Junit测试

作者:互联网

前言  

一般在测试Java用例时使用的都是main方法,这样就需要我们不断地修改main方法,导致测试代码通常无法保留或者不规范,因此Java提供了Junit进行更为优雅的白盒测试方式。

步骤

  1. 定义一个测试类(测试用例)
    • 测试类名: 被测试类名+Test  CalculatorTest
    • 包名: xxx.xxx.xx.test  com.tnxts.test
      import org.springframework.boot.test.context.SpringBootTest;
      
      
      @SpringBootTest
      public class testCalculate {
      
      }
  2. 定义测试方法: 可以独立运行
    • 方法名: test测试的方法名  testAdd()
    • 返回值: void
    • 参数列表: 空参
      import org.junit.Test;
      import org.springframework.boot.test.context.SpringBootTest;
      
      
      @SpringBootTest
      public class testCalculate {
      
          @Test
          public void testAdd(){
              Calculate c = new Calculate();
      
              int resultA = c.add(1,2);
              int resultB = c.sub(1,2);
      
              System.out.println(resultA);
              System.out.println(resultB);
          }
      }
  3. 使用断言判断正确与否
    import org.junit.Assert;
    import org.junit.Test;
    import org.springframework.boot.test.context.SpringBootTest;
    
    
    @SpringBootTest
    public class testCalculate {
    
        @Test
        public void testAdd(){
            Calculate c = new Calculate();
    
            int resultA = c.add(1,2);
            int resultB = c.sub(1,2);
    
            Assert.assertEquals(3,resultA);
        }
    }
  4. 结果(测试成功)

标签:Test,Springboot,public,SpringBootTest,测试,org,test,import,Junit
来源: https://www.cnblogs.com/tnxts/p/16439331.html