JUnit4 知识小结

2023-10-12 03:58
文章标签 知识 小结 junit4

本文主要是介绍JUnit4 知识小结,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

JUnit4 知识小结
java单元测试——JUnit4
JUnit是一个简单的框架,用于编写可重复的测试。它是单元测试框架的xUnit架构的一个实例。

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

package com.imooc.util;
import static org.junit.Assert.*;
import org.junit.Test;
public class CalculateTest {/** 1.测试方法上必须使用@Test进行修饰* 2.测试方法必须使用public void 进行修饰,不能带任何的参数* 3.新建一个源代码目录来存放我们的测试代码* 4.测试类的包应该和被测试类保持一致* 5.测试单元中的每个方法必须可以独立测试,测试方法间不能有任何的依赖* 6.测试类使用Test作为类名的后缀(不是必须)* 7.测试方法使用test作为方法名的前缀(不是必须)*/@Testpublic void testAdd() {assertEquals(6, new Calculate().add(3,3));}@Testpublic void testSubtract() {assertEquals(3, new Calculate().subtract(5,2));}@Testpublic void testMultiply() {assertEquals(4, new Calculate().multiply(2, 2));}@Testpublic void testDivide() {assertEquals(3, new Calculate().divide(6, 2));}
}

![这里写图片描述](https://img-blog.csdn.net/20170311023553919?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvUm9ja3lfWmhhbmcxOTkz/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEapackage com.imooc.util;
import static org.junit.Assert.*;
import org.junit.Test;
public class ErrorAndFailureTest {
/*
* 1.Failure一般由单元测试使用的断言方法判断失败所引起的,这经表示 测试点发现了问题
* ,就是说程序输出的结果和我们预期的不一样。
* 2.error是由代码异常引起的,它可以产生于测试代码本身的错误,也可以是被测试代码中的
* 一个隐藏的bug
* 3.测试用例不是用来证明你是对的,而是用来证明你没有错。
*/
@Test
public void testAdd() {
assertEquals(5, new Calculate().add(3,3));
}
@Test
public void testDivide() {
assertEquals(3, new Calculate().divide(6, 0));
}
}里写图片描述](https://img-blog.csdn.net/20170311023650312?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvUm9ja3lfWmhhbmcxOTkz/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
这里写图片描述

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 {/** 1.@BeforeClass修饰的方法会在所有方法被调用前被执行,* 而且该方法是静态的,所以当测试类被加载后接着就会运行它,* 而且在内存中它只会存在一份实例,它比较适合加载配置文件。* 2.@AfterClass所修饰的方法通常用来对资源的清理,如关闭数据库的连接* 3.@Before和@After会在每个测试方法的前后各执行一次。*/@BeforeClasspublic static void setUpBeforeClass() throws Exception {System.out.println("this is beforeClass...");}@AfterClasspublic static void tearDownAfterClass() throws Exception {System.out.println("this is afterClass...");}@Beforepublic void setUp() throws Exception {System.out.println("this is before...");}@Afterpublic void tearDown() throws Exception {System.out.println("this is after");}@Testpublic void test1() {System.out.println("this is test1...");}@Testpublic void test2(){System.out.println("this is test2...");}
}

这里写图片描述

package com.imooc.util;
import static org.junit.Assert.assertEquals;
import org.junit.Ignore;
import org.junit.Test;
public class AnotationTest {/** @Test:将一个普通的方法修饰成为一个测试方法*           @Test(expected=XX.class)*           @Test(timeout=毫秒 )* @BeforeClass:它会在所有的方法运行前被执行,static修饰* @AfterClass:它会在所有的方法运行结束后被执行,static修饰* @Before:会在每一个测试方法被运行前执行一次* @After:会在每一个测试方法运行后被执行一次* @Ignore:所修饰的测试方法会被测试运行器忽略* @RunWith:可以更改测试运行器 org.junit.runner.Runner*/@Test(expected=ArithmeticException.class)public void testDivide() {assertEquals(3, new Calculate().divide(6, 0));}@Ignore("...")@Test(timeout=2000)public void testWhile() {while(true) {System.out.println("run forever...");}}@Test(timeout=3000)public void testReadFile(){try {Thread.sleep(2000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}
package com.imooc.util;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({TaskTest1.class,TaskTest2.class,TaskTest3.class})
public class SuiteTest {/** 1.测试套件就是组织测试类一起运行的* 写一个作为测试套件的入口类,这个类里不包含其他的方法* 更改测试运行器Suite.class* 将要测试的类作为数组传入到Suite.SuiteClasses({})*/
}

这里写图片描述

package com.imooc.util;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class ParameterTest {/** 1.更改默认的测试运行器为RunWith(Parameterized.class)* 2.声明变量来存放预期值 和结果值* 3.声明一
静态方法,并使用@Parameters进行修饰* 4.为测试类声明一个带有参数的公共构造函数,并在其中为之声明变量赋值*/int expected =0;int input1 = 0;int input2 = 0;@Parameterspublic static Collection<Object[]> t() {return Arrays.asList(new Object[][]{{3,1,2},{4,2,2}}) ;}public ParameterTest(int expected,int input1,int input2) {this.expected = expected;this.input1 = input1;this.input2 = input2;}@Testpublic void testAdd() {assertEquals(expected, new Calculate().add(input1, input2));}
}

这里写图片描述
这里写图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="configLocation" value="classpath:hibernate.cfg.xml"/></bean><bean id="date" class="java.util.Date"/>
</beans>
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration><session-factory><property name="dialect">org.hibernate.dialect.MySQLDialect</property><property name="connection.url">jdbc:mysql://127.0.0.1:3306/mytest</property><property name="connection.username">root</property><property name="connection.password">mysql</property><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="myeclipse.connection.profile">com.mysql.jdbc.Driver</property></session-factory>
</hibernate-configuration>

package com.imooc.conform;

import org.hibernate.Session;
import org.junit.Test;
public class HibernateTest {@Testpublic void test() {Session session =  HibernateSessionFactory.getSession();System.out.println(session);}
}
package com.imooc.conform;import java.util.Date;import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringTest {private static ApplicationContext context = null;@BeforeClasspublic static void setUpBeforeClass() throws Exception {context = new ClassPathXmlApplicationContext("applicationContext.xml");}@Testpublic void test() {Date date =  (Date) context.getBean("date");System.out.println(date);}}

package com.imooc.conform;

import static org.junit.Assert.*;import org.hibernate.impl.SessionFactoryImpl;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringAndHibernate {private static ApplicationContext context;@BeforeClasspublic static void setUpBeforeClass() throws Exception {context = new ClassPathXmlApplicationContext("applicationContext.xml");}@Testpublic void test() {SessionFactoryImpl bean =  (SessionFactoryImpl) context.getBean("sessionFactory");System.out.println(bean);}
}
package com.imooc.conform;import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution.  Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {/*** Location of hibernate.cfg.xml file.* Location should be on the classpath as Hibernate uses  * #resourceAsStream style lookup for its configuration file.* The default classpath location of the hibernate config file is* in the default package. Use #setConfigFile() to update* the location of the configuration file for the current session.   */private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();private  static Configuration configuration = new Configuration();    private static org.hibernate.SessionFactory sessionFactory;private static String configFile = CONFIG_FILE_LOCATION;static {try {configuration.configure(configFile);sessionFactory = configuration.buildSessionFactory();} catch (Exception e) {System.err.println("%%%% Error Creating SessionFactory %%%%");e.printStackTrace();}}private HibernateSessionFactory() {}/*** Returns the ThreadLocal Session instance.  Lazy initialize* the <code>SessionFactory</code> if needed.**  @return Session*  @throws HibernateException*/public static Session getSession() throws HibernateException {Session session = (Session) threadLocal.get();if (session == null || !session.isOpen()) {if (sessionFactory == null) {rebuildSessionFactory();}session = (sessionFactory != null) ? sessionFactory.openSession(): null;threadLocal.set(session);}return session;}/***  Rebuild hibernate session factory**/public static void rebuildSessionFactory() {try {configuration.configure(configFile);sessionFactory = configuration.buildSessionFactory();} catch (Exception e) {System.err.println("%%%% Error Creating SessionFactory %%%%");e.printStackTrace();}}/***  Close the single hibernate session instance.**  @throws HibernateException*/public static void closeSession() throws HibernateException {Session session = (Session) threadLocal.get();threadLocal.set(null);if (session != null) {session.close();}}/***  return session factory**/public static org.hibernate.SessionFactory getSessionFactory() {return sessionFactory;}/***  return session factory**     session factory will be rebuilded in the next call*/public static void setConfigFile(String configFile) {HibernateSessionFactory.configFile = configFile;sessionFactory = null;}/***  return hibernate configuration**/public static Configuration getConfiguration() {return configuration;}
}

这篇关于JUnit4 知识小结的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/193061

相关文章

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

sqlite3 相关知识

WAL 模式 VS 回滚模式 特性WAL 模式回滚模式(Rollback Journal)定义使用写前日志来记录变更。使用回滚日志来记录事务的所有修改。特点更高的并发性和性能;支持多读者和单写者。支持安全的事务回滚,但并发性较低。性能写入性能更好,尤其是读多写少的场景。写操作会造成较大的性能开销,尤其是在事务开始时。写入流程数据首先写入 WAL 文件,然后才从 WAL 刷新到主数据库。数据在开始

系统架构师考试学习笔记第三篇——架构设计高级知识(20)通信系统架构设计理论与实践

本章知识考点:         第20课时主要学习通信系统架构设计的理论和工作中的实践。根据新版考试大纲,本课时知识点会涉及案例分析题(25分),而在历年考试中,案例题对该部分内容的考查并不多,虽在综合知识选择题目中经常考查,但分值也不高。本课时内容侧重于对知识点的记忆和理解,按照以往的出题规律,通信系统架构设计基础知识点多来源于教材内的基础网络设备、网络架构和教材外最新时事热点技术。本课时知识

分布式系统的个人理解小结

分布式系统:分的微小服务,以小而独立的业务为单位,形成子系统。 然后分布式系统中需要有统一的调用,形成大的聚合服务。 同时,微服务群,需要有交流(通讯,注册中心,同步,异步),有管理(监控,调度)。 对外服务,需要有控制的对外开发,安全网关。

【Python知识宝库】上下文管理器与with语句:资源管理的优雅方式

🎬 鸽芷咕:个人主页  🔥 个人专栏: 《C++干货基地》《粉丝福利》 ⛺️生活的理想,就是为了理想的生活! 文章目录 前言一、什么是上下文管理器?二、上下文管理器的实现三、使用内置上下文管理器四、使用`contextlib`模块五、总结 前言 在Python编程中,资源管理是一个重要的主题,尤其是在处理文件、网络连接和数据库

dr 航迹推算 知识介绍

DR(Dead Reckoning)航迹推算是一种在航海、航空、车辆导航等领域中广泛使用的技术,用于估算物体的位置。DR航迹推算主要通过已知的初始位置和运动参数(如速度、方向)来预测物体的当前位置。以下是 DR 航迹推算的详细知识介绍: 1. 基本概念 Dead Reckoning(DR): 定义:通过利用已知的当前位置、速度、方向和时间间隔,计算物体在下一时刻的位置。应用:用于导航和定位,

【H2O2|全栈】Markdown | Md 笔记到底如何使用?【前端 · HTML前置知识】

Markdown的一些杂谈 目录 Markdown的一些杂谈 前言 准备工作 认识.Md文件 为什么使用Md? 怎么使用Md? ​编辑 怎么看别人给我的Md文件? Md文件命令 切换模式 粗体、倾斜、下划线、删除线和荧光标记 分级标题 水平线 引用 无序和有序列表 ​编辑 任务清单 插入链接和图片 内嵌代码和代码块 表格 公式 其他 源代码 预

图神经网络(2)预备知识

1. 图的基本概念         对于接触过数据结构和算法的读者来说,图并不是一个陌生的概念。一个图由一些顶点也称为节点和连接这些顶点的边组成。给定一个图G=(V,E),  其 中V={V1,V2,…,Vn}  是一个具有 n 个顶点的集合。 1.1邻接矩阵         我们用邻接矩阵A∈Rn×n表示顶点之间的连接关系。 如果顶点 vi和vj之间有连接,就表示(vi,vj)  组成了

JAVA初级掌握的J2SE知识(二)和Java核心的API

/** 这篇文章送给所有学习java的同学,请大家检验一下自己,不要自满,你们正在学习java的路上,你们要加油,蜕变是个痛苦的过程,忍受过后,才会蜕变! */ Java的核心API是非常庞大的,这给开发者来说带来了很大的方便,经常人有评论,java让程序员变傻。 但是一些内容我认为是必须掌握的,否则不可以熟练运用java,也不会使用就很难办了。 1、java.lang包下的80%以上的类

JAVA初级掌握的J2SE知识(一)

时常看到一些人说掌握了Java,但是让他们用Java做一个实际的项目可能又困难重重,在这里,笔者根据自己的一点理解斗胆提出自己的一些对掌握Java这个说法的标准,当然对于新手,也可以提供一个需要学习哪些内容的参考。另外这个标准仅限于J2SE部分,J2EE部分的内容有时间再另说。 1、语法:必须比较熟悉,在写代码的时候IDE的编辑器对某一行报错应该能够根据报错信息知道是什么样的语法错误并且知道