This article mainly introduces JUnit, a detailed explanation of Java unit testing. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
Unit testing is writing test code, which should accurately and quickly ensure the correctness of the basic modules of the program.
JUnit is a Java unit testing framework that is installed by default in Eclipse.
JUnit4
JUnit4 identifies test methods through annotations. The main annotations currently supported are:
@BeforeClass will only be executed once globally, and it is the first one to run
@Before in the test method Run before running
@Test test method
@After Allow after test method runs
@AfterClass will only be executed globally once and is the last one to run
@Ignore Ignore this method
The following is based on Eclipse introduction Basic application of JUnit
Basic test
1. Create a new project called JUnitTest. We write a Calculator class, which can be easily implemented Calculator classes for addition, subtraction, multiplication, division, squares, and square roots, and then unit tests these functions.
public class Calculator { private static int result; // 静态变量,用于存储运行结果 public void add(int n) { result = result + n; } public void substract(int n) { result = result - 1; //Bug: 正确的应该是 result =result-n } public void multiply(int n) { } // 此方法尚未写好 public void pide(int n) { result = result / n; } public void square(int n) { result = n * n; } public void squareRoot(int n) { for (; ;) ; //Bug : 死循环 } public void clear() { // 将结果清零 result = 0; } public int getResult(){ return result; } }
1. Introduce the JUnit4 unit test package into this project: right-click on the project and click "Properties", as shown in the figure
In the pop-up properties window, first select "Java Build Path" on the left, then select the "Libraries" tab on the upper right, and then click the "Add Library..." button on the far right, as shown in the figure below Display
Then select JUnit4 in the new pop-up dialog box and click OK , as shown in the picture above, the JUnit4 software package is included in our project.
2. Generate JUnit test framework: Right-click the class in Eclipse's Package Explorer to pop up the menu and select "New JUnit Test Case". As shown in the picture below:
The complete CalculatorTest code is as follows:
public class CalculatorTest { private static Calculator calculator = new Calculator(); @Before public void setUp() throws Exception { calculator.clear(); } @Test public void testAdd() { calculator.add(3); calculator.add(4); assertEquals(7, calculator.getResult()); } @Test public void testSubstract() { calculator.add(8); calculator.substract(3); assertEquals(5, calculator.getResult()); } @Ignore("Multiply() Not yet implemented") @Test public void testMultiply() { fail("Not yet implemented"); } @Test public void testpide() { calculator.add(8); calculator.pide(2); assertEquals(4, calculator.getResult()); } }1. Run the test code: After modifying the above code, we right-click on the CalculatorTest class and select "Run As a JUnit Test" to run our test, as shown in the figure below
Limited time test
@Test(timeout = 1000) public void squareRoot() { calculator.squareRoot(4); assertEquals(2, calculator.getResult()); }The Timeout parameter indicates the time you want to set. , the unit is milliseconds, so 1000 represents 1 second.
测试异常
JAVA中的异常处理也是一个重点,因此你经常会编写一些需要抛出异常的函数。那么,如果你觉得一个函数应该抛出异常,但是它没抛出,这算不算Bug呢?这当然是Bug,并JUnit也考虑到了这一点,来帮助我们找到这种Bug。例如,我们写的计算器类有除法功能,如果除数是一个0,那么必然要抛出“除0异常”。因此,我们很有必要对这些进行测试。代码如下:
@Test(expected = ArithmeticException.class) public void pideByZero(){ calculator.pide(0); }
如上述代码所示,我们需要使用@Test标注的expected属性,将我们要检验的异常传递给他,这样JUnit框架就能自动帮我们检测是否抛出了我们指定的异常。
参数化测试
我们可能遇到过这样的函数,它的参数有许多特殊值,或者说他的参数分为很多个区域。
例如,测试一下“计算一个数的平方”这个函数,暂且分三类:正数、0、负数。在编写测试的时候,至少要写3个测试,把这3种情况都包含了,这确实是一件很麻烦的事情。测试代码如下:
public class AdvancedTest { private static Calculator calculator = new Calculator(); @Before public void clearCalculator(){ calculator.clear(); } @Test public void square1() { calculator.square(2); assertEquals(4, calculator.getResult()); } @Test public void square2(){ calculator.square(0); assertEquals(0, calculator.getResult()); } @Test public void square3(){ calculator.square(-3); assertEquals(9, calculator.getResult()); } }
为了简化类似的测试,JUnit4提出了“参数化测试”的概念,只写一个测试函数,把这若干种情况作为参数传递进去,一次性的完成测试。代码如下:
@RunWith(Parameterized.class) public class SquareTest{ private static Calculator calculator = new Calculator(); private int param; private int result; @Parameters public static Collection data() { return Arrays.asList(new Object[][]{ {2, 4}, {0, 0}, {-3, 9}, }); } //构造函数,对变量进行初始化 public SquareTest(int param, int result){ this.param = param; this.result = result; } @Test public void square(){ calculator.square(param); assertEquals(result, calculator.getResult()); } }
执行了3次该测试类,依次采用了数据集合中的数据{处理值,预期处理结果},结果如下:
代码分析如下:
为这种测试专门生成一个新的类,而不能与其他测试共用同一个类,此例中我们定义了一个SquareTest类。
为这个类指定一个Runner,而不能使用默认的Runner,@RunWith(Parameterized.class)这条语句就是为这个类指定了一个ParameterizedRunner
定义一个待测试的类,并且定义两个变量,一个用于存放参数,一个用于存放期待的结果。
定义测试数据的集合,也就是上述的data()方法,该方法可以任意命名,但是必须使用@Parameters标注进行修饰。
定义构造函数,其功能就是对先前定义的两个参数进行初始化
The above is the detailed content of Detailed explanation of JUnit in Java unit testing. For more information, please follow other related articles on the PHP Chinese website!

JUnit框架中的注解用于声明和配置测试方法,主要注解包括:@Test(声明测试方法)、@Before(测试方法执行前运行的方法)、@After(测试方法执行后运行的方法)、@BeforeClass(所有测试方法执行前运行的方法)、@AfterClass(所有测试方法执行后运行的方法),这些注解有助于组织和简化测试代码,并通过提供明确的意图和配置来提高测试代码的可读性和可维护性。

在多线程环境中使用JUnit时,有两种常见方法:单线程测试和多线程测试。单线程测试在主线程上运行,避免并发问题,而多线程测试在工作线程上运行,需要同步测试方法来确保共享资源不受干扰。常见使用案例包括测试多线程安全方法,例如使用ConcurrentHashMap存储键值对,并发线程对键值对进行操作并验证其正确性,体现了多线程环境中JUnit的应用。

JUnit是Java的单元测试框架,提供了简洁的工具来测试应用程序组件。安装依赖项后,可通过编写一个包含@Test注解的单元测试类来测试一个类,并使用assertEquals等断言方法验证预期值和实际值。JUnit提供了许多功能,例如准备方法、失败消息和超时机制。

JUnit单元测试框架是一个广泛使用的工具,主要优点包括自动化测试、快速反馈、提高代码质量和可移植性。但它也有局限性,包括范围有限、维护成本、依赖性、内存消耗和缺乏持续集成支持。对于Java应用程序的单元测试,JUnit是一个强大的框架,提供了许多好处,但使用时需要考虑其局限性。

JUnit是Spring项目中广泛使用的Java单元测试框架,可以通过以下步骤应用:添加JUnit依赖项:org.junit.jupiterjunit-jupiter5.8.1test编写测试用例:使用@ExtendWith(SpringExtension.class)启用扩展,使用@Autowired注入Bean,使用@BeforeEach和@AfterEach准备和清理,用@Test标记测试方法。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

在JUnit中,可以通过以下步骤在调试模式下运行测试用例:使用@RunWith注解关联BlockJUnit4ClassRunner运行器。设置断点以暂停执行并检查变量。使用System.out.println()输出信息以跟踪代码执行。使用JUnitAssert断言方法验证预期值和实际值。

JUnit单元测试框架可以有效解决常见的内存泄漏问题。常见的泄漏问题包括持久静态变量引用和未关闭资源。JUnit提供了泄漏检测器和分析内存占用情况的工具来定位泄漏源。解决方法包括使用局部变量、弱引用、正确关闭资源和采用try-with-resources语句。通过遵循这些指南,开发人员可以创建可靠且稳定的JUnit测试环境。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
