IntelliJ Idea + Maven + Junit

时间:2023-11-18 21:33:08

Caculate.java

package com.yxj.TestJunit;

/**
* Created by ubd on 15-4-17.
*/
public class Caculate { public int add(int i, int j) {
return i+j;
}
}

TestJunit.java

package com.yxj.TestJunit;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test; import static org.junit.Assert.assertEquals; /**
* Created by undoner on 15-4-17.
*/
public class TestJunit {
@Before
//使用了该元数据的方法在每个测试方法执行之前都要执行一次。
public void testBefore(){
System.out.println("testBefore");
}
@After
//使用了该元数据的方法在每个测试方法执行之后要执行一次。
public void testAfter(){
System.out.println("testAfter");
}
@Ignore
//该元数据标记的测试方法在测试中会被忽略。
// 当测试的方法还没有实现,或者测试的方法已经过时,或者在某种条件下才能测试该方法(比如需要一个数据库联接,而在本地测试的时候,数据库并没有连接),那么使用该标签来标示这个方法。同时,你可以为该标签传递一个String的参数,来表明为什么会忽略这个测试方法。比如:@lgnore(“该方法还没有实现”),在执行的时候,仅会报告该方法没有实现,而不会运行测试方法。
public void testIgnore(){
System.out.println("testIgnore");
}
@Test(timeout=10000)
//该元数据传入了一个时间(毫秒)给测试方法,如果测试方法在制定的时间之内没有运行完,则测试也失败。
public void testJunit(){
Caculate cal=new Caculate() ;
assertEquals(3,cal.add(1,1));
}
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.yxj.webapp</groupId>
<artifactId>webapp</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
</dependency>
</dependencies> </project>