您的位置:首页 > 编程语言 > Java开发

java中使用junit测试

2016-02-25 16:49 645 查看
最初写代码只要功能走通就不管了,然后如果出了什么问题再去修改,这是因为没做测试的工作。测试其实很简单。

1.准备

当前使用idea编写代码,用maven构建工程,使用maven的test功能来进行批量测试。测试工具为junit。

2.编写功能代码

将主要的业务功能的代码完成。

package com.test.java.designPattern.factory;

import junit.framework.TestResult;
import junit.framework.TestSuite;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
* Created by mrf on 2016/2/25.
*/
public class SendFactoryTest {

protected long startTime;
protected long endTime;

@Before
public void setUp() throws Exception {
this.startTime= System.currentTimeMillis();
System.out.println("=========开始测试===========");
}

@After
public void tearDown() throws Exception {
this.endTime = System.currentTimeMillis();
System.out.println("测试用时:"+(endTime-startTime));
System.out.println("=========测试结束===========");
}

@Test
public void testProduce() throws Exception {
SendFactory sendFactory = new SendFactory();
Sender sender = sendFactory.produce("email");
sender.send();
}

@Test
public void testM(){
System.out.println(12);
}

}


View Code

5.注意

maven测试一般文件位于test/java下对应的包下的的测试类,类名为要测试的类名+Test,要测试的方法为test+要测试的方法名。如上。

6.运行maven的test或install自动执行测试

可以直接在方法名上右键运行,也可以在maven中test或install。

如果光标位于方法体内,右键会出现运行这个测试方法,将光标移出方法,右键直接运行test用例,会运行所有@Test注解下的方法。

maven的test或install则直接测试所有的方法。

=========开始测试===========
Disconnected from the target VM, address: '127.0.0.1:6678', transport: 'socket'
This is emailSender!
测试用时:2
=========测试结束===========
=========开始测试===========
12
测试用时:0
=========测试结束===========


7.Assert

Junit4提供了一个Assert类(虽然package不同,但是大致差不多)。Assert类中定义了很多静态方法来进行断言。列表如下:

assertTrue(String message, boolean condition) 要求condition == true

assertFalse(String message, boolean condition) 要求condition == false

fail(String message) 必然失败,同样要求代码不可达

assertEquals(String message, XXX expected,XXX actual) 要求expected.equals(actual)

assertArrayEquals(String message, XXX[] expecteds,XXX [] actuals) 要求expected.equalsArray(actual)

assertNotNull(String message, Object object) 要求object!=null

assertNull(String message, Object object) 要求object==null

assertSame(String message, Object expected, Object actual) 要求expected == actual

assertNotSame(String message, Object unexpected,Object actual) 要求expected != actual

assertThat(String reason, T actual, Matcher matcher) 要求matcher.matches(actual) == true
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: