Junit代码

测试用例

----------Calculate.java

package com.imooc.util;

public class Calculate {
    public int add(int a,int b){
     return a + b;
    }
   
    public int subtract(int a,int b){
     return a - b;
    }
   
    public int multiply(int a,int b){
     return a * b;
    }
   
    public int divide(int a,int b){
     return a / b;
    }
}

-----------------------------------------------------------------------

 

---------CalculateTest.java

package com.imooc.util;

import static org.junit.Assert.*;

import org.junit.Test;

public class CalculateTest {


    @Test
    public void testAdd(){
     assertEquals(6,new Calculate().add(3, 3));------6(expected预期值)/3(actual结果值)
    }
   
    @Test
    public void testSubtract(){
     assertEquals(0,new Calculate().subtract(3, 3));
    }
   
   
    @Test
    public void testMultiply(){
     assertEquals(9,new Calculate().multiply(3, 3));
    }
   
    @Test
    public void testDivide(){
     assertEquals(1,new Calculate().divide(3, 3));
    }
}

-----------------------------------------------------------------------

------高级Fixture(固定)

package com.imooc.util;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class JunitFlowTest {

 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
  System.out.println("this is BeforeClass... ");
 }

 @AfterClass
 public static void tearDownAfterClass() throws Exception {
  System.out.println("this is AfterClass... ");
 }

 @Before
 public void setUp() throws Exception {
  
 }

 @After
 public void tearDown() throws Exception {
  System.out.println("this is After... ");
 }

 @Test
 public void test1() {
  System.out.println("this is test1... ");
 }
 @Test
 public void test2() {
  System.out.println("this is test2... ");
 }

}

 

console:

this is BeforeClass...
this is test1...
this is After...
this is test2...
this is After...
this is AfterClass...

-----------------------------------------------------------------------------------

参数化

package com.imooc.util;
import java.util.Arrays;
import java.util.Collection;

import org.junit.runner.RunWith;
import  org.junit.runners.Parameterized.Parameters;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class ParameterTest {
     int expected = 0;
     int input1 = 0;
     int input2 = 0;
    
 @Parameters
 public static Collection data() {
  return Arrays.asList(new Object[][]{
    {3,1,2},------1,2就是参数,3就是预期的结果。   

    {4,2,2}------2,2就是参数,4就是预期的结果。
 });
}
//构造函数,对变量进行初始化
 public ParameterTest (int expected,int input1,int input2){
  this.expected = expected;
  this.input1 = input1;
  this.input2 = input2;
 }
 
@Test
 public void testAdd(){
 assertEquals(expected,new Calculate().add(input1, input2));
}
}

 

 

你可能感兴趣的:(Junit代码)