Junit 框架概述:
Junit 可以选择执行哪些测试方法,也可以一键执行全部的测试方法
Junit 可以生成测试报告,测试无误为绿色,测试失败为红色,有返回值类型的方法可以加入断言
单个方法的测试失败不会影响其他的方法
实现要求:
测试方法必须是公共的无参无返回值类型的非静态方法
测试方法上标注@Test
Junit 常用注解:
注解Junit 4 | Junit 5 | 说明 |
---|---|---|
@Test | 测试方法 | |
@Before | @BeforeEach | 用来修饰实例方法,该方法会在每一个测试方法执行前执行一次 |
@After | @AfterEach | 用来修饰实例方法,该方法会在每一个测试方法执行后执行一次 |
@BeforeClass | @BeforeAll | 用来静态修饰方法,该方法会在所有测试方法之前只执行一次 |
@AfterClass | @AfterAll | 用来静态修饰方法,该方法会在所有测试方法之后只执行一次 |
before 初始化资源
after 释放资源
代码实现:
测试类代码实现:
package com.xm;
import org.junit.*;
public class Demo1 {
@Before
public void before()
{
System.out.println("before方法执行一次");
}
@After
public void after()
{
System.out.println("after方法执行一次");
}
@BeforeClass
public static void BeforeClass()
{
System.out.println("beforeClass执行一次");
}
@AfterClass
public static void AfterClass()
{
System.out.println("AfterClass执行一次");
}
@Test
public void test1()
{
Server server = new Server();
String str=server.loginName("admin");
Assert.assertEquals("功能出现问题","登录成功",str);
}
@Test
public void test2()
{
Server server = new Server();
server.selectName();
}
}
需要测试的类:
package com.xm;
public class Server {
public String loginName(String name)
{
if("admin".equals(name))
return "登录成功";
else
return "用户名有问题";
}
public void selectName()
{
System.out.println(10/1);
System.out.println("查询完毕");
}
}
模拟Junit框架 代码实现:
package com.xm;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestJunit {
@MyTest
public void test1() {
System.out.println("test1");
}
public void test2() {
System.out.println("test2");
}
@MyTest
public void test3() {
System.out.println("test3");
}
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class<TestJunit> c1 = TestJunit.class;
Method[] methods = c1.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MyTest.class)) {
Constructor<TestJunit> constructor = c1.getConstructor();
TestJunit junit = constructor.newInstance();
method.invoke(junit);
}
}
}
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyTest {
}