关于Junit

来源:互联网 发布:淘宝海外代购可信吗 编辑:程序博客网 时间:2024/05/16 11:03

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.");          }}@Testpublic 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.

0 0