关于Junit

JUnit简单介绍

  • JUnit是什么
    JUnit是xUnit的一个子集,xUnit是一套基于测试驱动开发的测试框架,除了用来测试Java程序的JUnit,xUnit还包含PythonUnit和CppUnit等测试框架.
  • JUnit怎么用
    1. JUnit API介绍
      常用:
      断言assertEquals(expected,actual)判断实际输出与预测输出是否相等
    2. JUnit 代码框架
import org.junit.*;

public class TestFoobar {
    @BeforeClass
    public static void setUpClass() throws Exception {
        // Code executed before the first test method       
    }

    @Before
    public void setUp() throws Exception {
        // Code executed before each test    
    }

    @Test
    public void testOneThing() {
        // Code that tests one thing
    }

    @Test
    public void testAnotherThing() {
        // Code that tests another thing
    }

    @Test
    public void testSomethingElse() {
        // Code that tests something else
    }

    @After
    public void tearDown() throws Exception {
        // Code executed after each test   
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
        // Code executed after the last test method 
    }
}
  • 常见问题

问题:private,protect函数的测试
解决:使用Java反射的getDeclaredMethod()函数
例子:

private String emotion(String content,String scName){
          //私聊
          if(content.contains("//Greet")){
              return("Nice to meet you,"+scName+".");
          }else{
              return("There is no perset emotion for your words.");
          }
}

@Test
public void testemotiom() throws Exception {
    ChatServer cs = new ChatServer();
    Object a=null;
    try{
        Method method = cs.getClass().getDeclaredMethod("emotion",new Class[] {String.class, String.class});
        method.setAccessible(true);                //让其方法可访问

        a = method.invoke(cs, new Object[] {"//Greet", "liqi"});
    }catch(Exception ex){}

    assertEquals("Nice to meet you,liqi.",a.toString());
}

问题:mock final method
解决:Mockito不支持,JMock,PowerMock,PreMock支持

their real behavior is executed without any exception. Mockito cannot warn you about mocking final methods so be vigilant.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值