`
aaron_ch
  • 浏览: 177344 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

JUnit4 experience

    博客分类:
  • TDD
阅读更多

JUnit4 Version inheritates the annotation features from java5.0v,so it simplized many workload for unit test.
Now I am using the feature to speedup my test work.
1.Create your class that will be tested.
package com.aaron;

public class Calculator {
//  static variant for store result
    private static int result;
    public void add(int n){
        result = result + n;
    }
    public void substract(int n){
        //Bug: correctly method for: result =result-n
        result = result - 1;
    }
    public void multiply(int n){
        //TODO
    }        
    public void divide(int n){
        result = result / n;
    }
    public void square(int n){
        result = n * n;
    }
    public void squareRoot(int n){
        //Bug :Dead loop
        for (; ;) ;          
    }
    public void clear(){    
       //clear the result,due to the Fixture feature in junit.
        result = 0;
    }
    public int getResult(){
        return result;
    }
}

Next create the testcase for the class
package com.aaron;
import static org.junit.Assert.*;import static org.junit.Assert.*;
then you can directly use the assertEquals() method in the testcase.
2.Test class declare,you know that,no specail class extends from junit,you can define the test class with your idea.
3.Create the test object.as the above:private static Calculator calculator = new Calculator();
4.Test methods declare,
you can use some marks for the test methods.such as @Test,@Ignore,@Before,@After.
5.Write your test method,please kindly remaind that no return value in the test method.
6.Fixture utility,
@Before
public void setUp() throws Exception{
     calculator.clear();
}
That means if you want to the test methods independent,so you need  initialize the test class when you test a method,so in junit4v, you just declare @Before in the setUp() method,and every time you refer to the class instance with new.
7.High level Fixture:
if you want to test a class which read/write a big block file in every method. you know it's very heavy to read/write a big block file every time.you had better read the file once,then every method can read/write the file by the initialization. in junit,you can use @BeforeClass and @AfterClass to finish that.
and Only one method can be declared public and static.
8.Time test,
 @Test(timeout = 1000),if you have a dead loop to test,how do you control that? the best way is using timeout.(microsecond).
9.Exception handle.
@Test(expected = ArithmeticException.class),if you divide a zero,then? so you need an exception to catch it.
10.Runner.
In my test code,you do not know which runner used,also there are many runners in the Junit framework,Now
you can explicit to declare the runner before the class which you want with
@RunWith(TestClassRunner.class)
11.Parameter
package com.aaron;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collection;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

public class CalculatorTest {

 private static Calculator calculator = new Calculator();
 @Before
 public void setUp() throws Exception {
  calculator.clear();
 }

 @Test
 public void testAdd() {
  calculator.add(2);
        calculator.add(3);
        assertEquals(5, calculator.getResult());
 }

 @Test
 public void testSubstract() {
  calculator.add(10);
        calculator.substract(2);
        assertEquals(8, calculator.getResult());
 }
    @Ignore("Not implement")
 @Test
 public void testMultiply() {
  fail("Not yet implemented");
 }

 @Test
 public void testDivide() {
   calculator.add(8);
      calculator.divide(2);
      assertEquals(4, calculator.getResult());
 }

}

Run the testcase,that will one error occurance.

And above is the basic test process.
Now let's take some more introduction for the JUnit4
1.import the necessary package

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{
     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},
                 {-2, 9},
         });
     }

     //Constructor,reinitialize the parameters
     public ParameterTest(int param, int result){
         this.param = param;
         this.result = result;
     }

     @Test
     public void square(){
         calculator.square(param);
         assertEquals(result, calculator.getResult());
     }

 }

12.Package multi-test,due to many test classes for a class,so one by one to test,it's not convenient for user,so in Junit,you can use suite to package all tests for you.
package com.aaron;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
        CalculatorTest.class,
        ParameterTest.class
        })
public class AllCalculatorTests{
}

OK,that's all,enjoy that!

分享到:
评论

相关推荐

    Java-development-experience.zip_experience_立项

    单元测试是编码过程中的重要组成部分,JUnit等工具可以帮助我们编写和执行测试用例,确保代码的正确性。在编程过程中,要时刻关注代码的性能,避免过度设计,同时利用Java的并发特性提高多线程程序的效率。 最后,...

    Futuroscope_Experience_Setup-源码.rar

    4. **交互设计**:为了提供未来感的体验,开发者可能使用了事件驱动编程和响应式设计,使用户与软件的互动更加自然流畅。例如,利用键盘、鼠标、触摸屏甚至手势识别技术。 5. **数据处理**:程序可能涉及大量的数据...

    pants-7.x-1.x-dev_test_experience_

    测试工具的选择也会影响测试体验,例如JUnit for Java,pytest for Python,或是Selenium for Web应用自动化测试。测试框架如Jenkins、GitLab CI/CD和Travis CI可以自动化测试和部署流程,提高效率。 性能测试则...

    Clean.Code.Summary.B01AAS8T4A.pdf

    Essential elements extracted by a developer and manager with 20 years of experience in software development and data analysis. Saves your time from re-reading the 450+ page book to re-absorb, remember...

    Doing.More.with.Java.Android.and.Tomcat.B016JAE0XM

    The tone of the book is intended to be light rather than pedantic and hints and tips based on the author’s life experience are included. Table of Contents Chapter 1 Stuff You Need to Know Chapter 2 ...

    Struts Hibernate Ibatis Spring RAD WID

    -- Be familiar with popular development tools, such as CVS, Ant, JUnit, etc  -- Be familiar with popular web development frameworks and tools, such as Struts, Spring, Hibernate. -- Good knowledge of...

    ngx-aem:一个显示如何在Adobe Experience Manager中实现Angular 6+的存储库

    将Angular6转换为AEM 这是基于AEM的应用程序的项目模板。 它旨在作为最佳实践示例集,也是开发... ui.launcher:包含粘合代码,该粘合代码将ui.tests捆绑包(和相关捆绑包)部署到服务器并触发远程JUnit执行 如何建造

    Spring Recipes: A Problem-Solution Approach, Second Edition

    * Spring’s unit and integration testing support (on JUnit 3.8, JUnit 4, and TestNG). * How to secure applications using Spring Security. Who this book is for This book is for Java developers who ...

    interview_tiaa

    Years of Experience: 8 Years 9 months 第二节 Build IDE: Intellij IDEA 2018.1.5 JDK Version: java version "10.0.1" 第三节 a)声纳皮棉扫描快照-![Sonarlint]( ) b)最终输出快照![输出]( ) c)...

    Implementing.Domain.Specific.Languages.with.Xtext.and.Xtend.2nd.Ed

    Previous experience with compiler implementation can be helpful but is not necessary since this book will explain all the development stages of a DSL. What You Will Learn Write Xtext grammar for a ...

    aem-sample-we-retail::prohibited:We.Retail已存档,请参阅《 WKND指南》:

    不再支持 , 是Adobe Experience Manager的替代参考站点。 模组 模板的主要部分是: 核心:包含所有核心功能(例如OSGi服务,侦听器或调度程序)以及与组件相关的Java代码(例如Servlet或请求过滤器)的Java捆绑包...

    测试程序c8t6.zip

    "CX"可能代表用户界面(UI)体验、客户交互(Customer Experience)或者某种特定的技术组件。下面我们将深入探讨测试程序的相关知识点。 1. **测试程序**:测试程序是一系列预先设计好的指令,用于检查软件是否符合...

    maven-and-osgi

    In terms of capabilities, Maven is an improvement to Apache Ant-thanks to numerous plug-ins and built-in integration with unit testing frameworks such as JUnit. Tired of writing the same build logic ...

    maven学习资料,通过这基本书可以很快上手,包含chm文档

    In terms of capabilities, Maven is an improvement to Apache Ant-thanks to numerous plug-ins and built-in integration with unit testing frameworks such as JUnit. Tired of writing the same build logic ...

    interview_solution

    面试解决方案第1节Name: Ganesh ShirsatYears of Experience: 10 years第2节: Build IDE: Eclipse Java EE IDE for Web Developers (Version: Photon Release (4.8.0))JDK Version: java version "1.8.0_171"第三节...

    aem-stubs-源码.rar

    Adobe Experience Manager (AEM) 是一款强大的内容管理和数字营销平台,广泛用于构建响应式网站、移动应用和数字体验。AEM Stubs 是一个开发工具,它允许开发者在不运行完整AEM实例的情况下进行单元测试和集成测试。...

Global site tag (gtag.js) - Google Analytics