zoukankan      html  css  js  c++  java
  • Junit使用

    首先需要jar包

    http://mvnrepository.com/artifact/junit/junit/4.12

    在IDEA使用的话 把原有的功能进行测试

    //判读字符串第一个不重复的字符
        @Override
        public char getStr(String str) {
            //indexOf();lastIndexOf();
            if (str == null || str.length() == 0 || str.equals("") || str.trim().isEmpty()) {
                return 0;
            }
            Map<Character, Integer> counts = new LinkedHashMap<Character, Integer>(
                    str.length());
            for (char c : str.toCharArray()) {
                counts.put(c, counts.containsKey(c) ? counts.get(c) + 1 : 1);
            }
            for (Map.Entry<Character, Integer> entry : counts.entrySet()) {
                if (entry.getValue() == 1) {
                    return entry.getKey();
                }
            }
            return 0;
        }
        //随机字符串
        @Override
        public String getRandStr(int length) {
            //定义一个字符串(A-Z,a-z,0-9)即62位;
            String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
            //由Random生成随机数
            Random random = new Random();
            StringBuilder sb = new StringBuilder();
            //长度为几就循环几次
            for (int i = 0; i < length; ++i) {
                //产生0-61的数字
                int number = random.nextInt(62);
                //将产生的数字通过length次承载到sb中
                sb.append(str.charAt(number));
            }
            //将承载的字符转换成字符串
            return sb.toString();
        }

    如何使用Junit进行测试呢?

    快捷键Ctrl + Shift + T

    选择create

    购选所需方法就可以了

    需要选择Junit

    即可运行测试

    绿色说明通过

     需要测试的方法

    package Test;
    
    public class StringUtilImpl implements StringUtil {
        //Rot13加密解密
        @Override
        public String getRot13(String str) {
            if (str == null || str.length() == 0 || str.equals("") || str.trim().isEmpty()) {
                return null;
            } else {
                char[] chr = str.toCharArray();
                StringBuffer buffer =new StringBuffer();
                for (int i = 0; i < chr.length; i++) {
                    if ((chr[i] >= 'A') && (chr[i] <= 'Z')) {
                        chr[i] += 13;
                        if (chr[i] > 'Z') {
                            chr[i] -= 26;
                        }
                    } else if ((chr[i] >= 'a') && (chr[i] <= 'z')) {
                        chr[i] += 13;
                        if (chr[i] > 'z') {
                            chr[i] -= 26;
                        }
                    }else if((chr[i] >= '0') && (chr[i] <= '9')){
                       chr[i] +=5;
                       if(chr[i] > '9'){
                           chr[i] -= 10;
                       }
                   }
                    // and return it to sender
                    buffer.append(chr[i]);
                }
                return buffer.toString();
            }
        }
        //字符串翻转
        @Override
        public String getReverse(String str) {
            if (str == null || str.length()==0 || str.equals("") || str.trim().isEmpty()) {
                return null;
            }
            char[] arr = str.toCharArray();
            String reverse = "";
            for (int i = arr.length - 1; i >= 0; i--) {
                reverse += arr[i];
            }
            return reverse;
        }
        //判读字符串是否为空
        @Override
        public boolean getIsEmpty(String str) {
            if (str == null || str.length()==0 || "".equals(str) || str.trim().isEmpty()) {
                return true;
            }
            return false;
        }
    }

    测试类

    package DemoJunit;
    
    import Test.StringUtilImpl;
    import org.junit.Assert;
    import org.junit.Ignore;
    import org.junit.Test;
    import Test.*;
    
    import static org.junit.Assert.*;
    
    public class StringUtilImplTest {
        StringUtil s = new StringUtilImpl();
    
        @Test
        //@Ignore("该客户没有给钱不给他密码加密所以给他挖个坑...")
        public void getRot13() {
            Assert.assertEquals(s.getRot13("abc大Das是的3"), "nop大Qnf是的8");
            Assert.assertEquals(s.getRot13("ynxsfy"), "lakfsl");
            Assert.assertEquals(s.getRot13("I'm from guangdong"), "V'z sebz thnatqbat");
            Assert.assertEquals(s.getRot13("StringUtil"), "FgevatHgvy");
            Assert.assertEquals(s.getRot13("  "), null);
            Assert.assertEquals(s.getRot13(null), null);
        }
    
        @Test
        public void getReverse() {
            Assert.assertEquals(s.getReverse("are you ok?"), "?ko uoy era");
            Assert.assertEquals(s.getReverse("I me here"), "ereh em I");
            Assert.assertEquals(s.getReverse(""), null);
            Assert.assertEquals(s.getReverse(null), null);
        }
    
        @Test
        public void getIsEmpty() {
            String str = "";
            Assert.assertEquals(s.getIsEmpty(null), true);
            Assert.assertEquals(s.getIsEmpty("   "), true);
            Assert.assertEquals(s.getIsEmpty(""), true);
            Assert.assertEquals(s.getIsEmpty(str), true);
            Assert.assertEquals(s.getIsEmpty("GG"), false);
        }
    }

     下面来介绍 Maven项目SSM结合Junit

    这里无需添加架包在使用Maven项目字段配置好Junit

    在项目的src根目录下面创建一个Test文件夹

    然后点击右键选择

    然后文件夹就会变绿色了

    使用:

    在service选择需要测试的方法然后会自动在Test文件下面生成测试类;

     

    代码:

    package com.gdnf.ssm.service;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.apache.log4j.spi.LoggerFactory;
    import org.junit.*;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import  org.apache.log4j.*;
    
    import java.util.logging.Logger;
    
    import static org.junit.Assert.*;
    
    public class BookServiceImplTest {
        static ClassPathXmlApplicationContext context;
        static Log logger ;
    
        @BeforeClass
        public static void init() {
            context = new ClassPathXmlApplicationContext("spring_root.xml");
            logger = LogFactory.getLog("");
        }
    
        @AfterClass
        public static void after() {
            logger.info("结束了");
        }
        //@Ignore
        @Test
        public void getCount() {
            BookService bean = context.getBean(BookService.class);
            logger.info(bean.getCount());
            logger.info(bean.getBookAll());
        }
    }

    结果

    这里配置的Log4j是输出到控制台

    "C:Program FilesJavajdk1.8.0_181injava" -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:二学年工具包idea文件IntelliJ IDEA 2017.3.5libidea_rt.jar=64358:D:二学年工具包idea文件IntelliJ IDEA 2017.3.5in" -Dfile.encoding=UTF-8 -classpath "D:二学年工具包idea文件IntelliJ IDEA 2017.3.5libidea_rt.jar;D:二学年工具包idea文件IntelliJ IDEA 2017.3.5pluginsjunitlibjunit-rt.jar;D:二学年工具包idea文件IntelliJ IDEA 2017.3.5pluginsjunitlibjunit5-rt.jar;C:Program FilesJavajdk1.8.0_181jrelibcharsets.jar;C:Program FilesJavajdk1.8.0_181jrelibdeploy.jar;C:Program FilesJavajdk1.8.0_181jrelibextaccess-bridge-64.jar;C:Program FilesJavajdk1.8.0_181jrelibextcldrdata.jar;C:Program FilesJavajdk1.8.0_181jrelibextdnsns.jar;C:Program FilesJavajdk1.8.0_181jrelibextjaccess.jar;C:Program FilesJavajdk1.8.0_181jrelibextjfxrt.jar;C:Program FilesJavajdk1.8.0_181jrelibextlocaledata.jar;C:Program FilesJavajdk1.8.0_181jrelibext
    ashorn.jar;C:Program FilesJavajdk1.8.0_181jrelibextsunec.jar;C:Program FilesJavajdk1.8.0_181jrelibextsunjce_provider.jar;C:Program FilesJavajdk1.8.0_181jrelibextsunmscapi.jar;C:Program FilesJavajdk1.8.0_181jrelibextsunpkcs11.jar;C:Program FilesJavajdk1.8.0_181jrelibextzipfs.jar;C:Program FilesJavajdk1.8.0_181jrelibjavaws.jar;C:Program FilesJavajdk1.8.0_181jrelibjce.jar;C:Program FilesJavajdk1.8.0_181jrelibjfr.jar;C:Program FilesJavajdk1.8.0_181jrelibjfxswt.jar;C:Program FilesJavajdk1.8.0_181jrelibjsse.jar;C:Program FilesJavajdk1.8.0_181jrelibmanagement-agent.jar;C:Program FilesJavajdk1.8.0_181jrelibplugin.jar;C:Program FilesJavajdk1.8.0_181jrelib
    esources.jar;C:Program FilesJavajdk1.8.0_181jrelib
    t.jar;D:二学年学习项目my_ssm	arget	est-classes;D:二学年学习项目my_ssm	argetclasses;C:UsersDZ.m2
    epositoryjunitjunit4.12junit-4.12.jar;C:UsersDZ.m2
    epositoryorghamcresthamcrest-core1.3hamcrest-core-1.3.jar;C:UsersDZ.m2
    epositoryorgspringframeworkspring-web5.1.0.RELEASEspring-web-5.1.0.RELEASE.jar;C:UsersDZ.m2
    epositoryorgspringframeworkspring-beans5.1.0.RELEASEspring-beans-5.1.0.RELEASE.jar;C:UsersDZ.m2
    epositoryorgspringframeworkspring-core5.1.0.RELEASEspring-core-5.1.0.RELEASE.jar;C:UsersDZ.m2
    epositoryorgspringframeworkspring-jcl5.1.0.RELEASEspring-jcl-5.1.0.RELEASE.jar;C:UsersDZ.m2
    epositoryorgspringframeworkspring-aop5.1.0.RELEASEspring-aop-5.1.0.RELEASE.jar;C:UsersDZ.m2
    epositoryorgspringframeworkspring-jdbc5.1.0.RELEASEspring-jdbc-5.1.0.RELEASE.jar;C:UsersDZ.m2
    epositoryorgspringframeworkspring-tx5.1.0.RELEASEspring-tx-5.1.0.RELEASE.jar;C:UsersDZ.m2
    epositoryorgspringframeworkspring-webmvc5.1.0.RELEASEspring-webmvc-5.1.0.RELEASE.jar;C:UsersDZ.m2
    epositoryorgspringframeworkspring-context5.1.0.RELEASEspring-context-5.1.0.RELEASE.jar;C:UsersDZ.m2
    epositoryorgspringframeworkspring-expression5.1.0.RELEASEspring-expression-5.1.0.RELEASE.jar;C:UsersDZ.m2
    epositoryorgmybatismybatis3.4.6mybatis-3.4.6.jar;C:UsersDZ.m2
    epositoryorgmybatismybatis-spring1.3.2mybatis-spring-1.3.2.jar;C:UsersDZ.m2
    epositoryorgmariadbjdbcmariadb-java-client2.3.0mariadb-java-client-2.3.0.jar;C:UsersDZ.m2
    epositorycommchangec3p0.9.5.2c3p0-0.9.5.2.jar;C:UsersDZ.m2
    epositorycommchangemchange-commons-java.2.11mchange-commons-java-0.2.11.jar;C:UsersDZ.m2
    epositoryjavaxservletjstl1.2jstl-1.2.jar;C:UsersDZ.m2
    epositorycomfasterxmljacksoncorejackson-databind2.9.7jackson-databind-2.9.7.jar;C:UsersDZ.m2
    epositorycomfasterxmljacksoncorejackson-annotations2.9.0jackson-annotations-2.9.0.jar;C:UsersDZ.m2
    epositorycomfasterxmljacksoncorejackson-core2.9.7jackson-core-2.9.7.jar;C:UsersDZ.m2
    epositorylog4jlog4j1.2.17log4j-1.2.17.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 com.gdnf.ssm.service.BookServiceImplTest
    DEBUG [main] - ==>  Preparing: select count(name) from book 
    DEBUG [main] - ==> Parameters: 
    DEBUG [main] - <==      Total: 1
    九月 30, 2018 2:23:59 下午 com.gdnf.ssm.service.BookServiceImplTest getCount
    信息: 10
    DEBUG [main] - ==>  Preparing: select * from book 
    DEBUG [main] - ==> Parameters: 
    DEBUG [main] - <==      Total: 10
    九月 30, 2018 2:23:59 下午 com.gdnf.ssm.service.BookServiceImplTest getCount
    信息: [Book{id=1, name='干法', cnt=25}, Book{id=2, name='Java程序设计', cnt=8}, Book{id=7, name='哲学', cnt=0}, Book{id=8, name='小说', cnt=13}, Book{id=9, name='啊哈哈', cnt=13}, Book{id=10, name='cc', cnt=11}, Book{id=11, name='卓悦', cnt=57}, Book{id=12, name='他们最幸福', cnt=1}, Book{id=13, name='admin', cnt=123456789}, Book{id=14, name='我不', cnt=6}]
    九月 30, 2018 2:23:59 下午 com.gdnf.ssm.service.BookServiceImplTest after
    信息: 结束了
    
    Process finished with exit code 0
    package com.gdnf.ssm.service;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.apache.log4j.spi.LoggerFactory;
    import org.junit.*;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.apache.log4j.*;

    import java.util.logging.Logger;

    import static org.junit.Assert.*;

    public class BookServiceImplTest {
    static ClassPathXmlApplicationContext context;
    static Log logger ;

    @BeforeClass
    public static void init() {
    context = new ClassPathXmlApplicationContext("spring_root.xml");
    logger = LogFactory.getLog("");
    }

    @AfterClass
    public static void after() {
    logger.info("结束了");
    }
    //@Ignore
    @Test
    public void getCount() {
    BookService bean = context.getBean(BookService.class);
    logger.info(bean.getCount());
    logger.info(bean.getBookAll());
    }
    }
  • 相关阅读:
    软件使用[17]
    软件使用[20]
    软件使用[12]
    软件使用[10]
    软件使用[22]
    软件使用[06]
    软件使用[11]SlickEdit
    软件使用[19]
    uva 10717【Mint】
    uva 10791【 Minimum Sum LCM】
  • 原文地址:https://www.cnblogs.com/dzcici/p/9728877.html
Copyright © 2011-2022 走看看