maven 打包前 Junit 测试

时间:2024-01-03 14:11:14

1. 在需要打包前测试的项目中添加依赖

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

2.在项目目录 src/test/java 下创建单元测试 Test*.java

package event;

import org.junit.Assert;
import org.junit.Test; public class Test2 { @Test
public void test() {
Assert.assertEquals(3, 2);
} }

3.运行 maven test

Results :

Failed tests:   test(event.Test2): expected:<3> but was:<2>
test(event.Test3): expected:<1> but was:<3> Tests run: 3, Failures: 2, Errors: 0, Skipped: 0

4.当然有时候需要加载配置文件

添加 pom

      <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>

测试

@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true)
@ContextConfiguration(locations = {"classpath*:applicationContext.xml"})
public class UserServiceTest { private static Logger LOGGER = LoggerFactory.getLogger(UserServiceTest.class); protected long startTime; protected long endTime; @Resource
private UserService userService; @Before
public void before() {
start();
} @After
public void after() {
end();
} @Test
public void saveTest() {
User user = new User();
user.setUserName( "test1" );
user.setUserPassword( "test2" );
int count = userService.save( user );
Assert.assertEquals( 1, count );
} /**
* 记录 开始运行时间
*
* @return
*/
protected long start() {
this.startTime = System.currentTimeMillis();
return startTime;
} /**
* 记录 结束运行时间
*
* @return
*/
protected long end() {
this.endTime = System.currentTimeMillis();
this.log();
return endTime;
} /**
* 输出记录
*/
protected void log() {
String text = "\n开始时间 : " + this.startTime + "\n结束时间 : " + this.endTime + "\n执行时间 : " + (this.endTime - this.startTime);
LOGGER.debug(text);
} }