通过junit写unit test

本文介绍如何使用JUnit进行单元测试,包括运行所有测试、指定特定测试用例及排除某些测试的方法。此外,还提供了如何配置Maven以实现这些操作的具体示例。

how to run test within junit & mvn:

During team development , there are more than 1 person edit your api or file which it's very common. And to improve your api stablity and quality, it's critical important to write unit test.

run all test
mvn test
run specific test

Sometimes we have thousands of unit test, but you need to test only some testcase you have just wrote for verify some case you can specific your only test case:

mvn -Dtest=TestApp1 test
run exclude some specific case

Meanwhile you may exclude some unrelated test case(or include some test case) for a quick verify.

for example, skip TestApp2.java, edit your pom.xml:

<build>
<plugins>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
      <excludes>
        <exclude>**/TestApp2.java</exclude>
      </excludes>
    </configuration>
  </plugin>
</plugins>   </build>
serval common case log:
  • when not pass test:

Running com.wade.core.TestApp1 Tests run: 1, Failures: 1, Errors: 0,
Skipped: 0, Time elapsed: 0.091 sec <<< FAILURE!
testHelloworld(com.wade.core.TestApp1) Time elapsed: 0.022 sec <<<
FAILURE! junit.framework.ComparisonFailure: expected:<Hello[W]orld>
but was:<Hello[w]orld> at
junit.framework.Assert.assertEquals(Assert.java:100)

  • pass test:

Running com.wade.core.TestApp1 Tests run: 1, Failures: 0, Errors: 0,
Skipped: 0, Time elapsed: 0.093 sec Running com.wade.core.TestApp2
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

  • compile error:

[INFO] BUILD FAILURE [INFO]
------------------------------------------------------------------------ [INFO] Total time: 1.392 s [INFO] Finished at:
2016-07-10T23:15:34+08:00 [INFO] Final Memory: 14M/165M [INFO]
------------------------------------------------------------------------ [ERROR] Failed to execute goal
org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile
(default-testCompile) on project unittest: Compilation failure:
Compilation failure: [ERROR]
/Users/dengwei/projects/github/javacourse/unittest/src/test/java/com/wade/TestApp2.java:[8,61]
';' expected [ERROR]
/Users/dengwei/projects/github/javacourse/unittest/src/test/java/com/wade/TestApp1.java:[8,59]
';' expected [ERROR] -> [Help 1] [ERROR]

Appendix:

Java 多线程程序的单元测试是一项具有挑战性的任务,因为多线程代码涉及并发、同步和资源共享等问题。为了确保测试的可靠性和可重复性,可以使用专门的工具和库来辅助测试,例如 GroboUtils 提供了一种简单而清晰的方式来编多线程单元测试。以下是一些关键策略和方法: ### 创建线程池并执行测试任务 通过创建多个线程并让它们并发执行测试逻辑,可以模拟实际运行环境中的并发行为。例如: ```java import junit.framework.TestCase; import java.util.concurrent.CountDownLatch; public class MultiThreadedTest extends TestCase { private volatile boolean testPassed = false; public void testConcurrentExecution() throws InterruptedException { int threadCount = 10; CountDownLatch latch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { new Thread(() -> { try { // 模拟并发操作 performConcurrentOperation(); } finally { latch.countDown(); } }).start(); } latch.await(); // 等待所有线程完成 assertTrue(testPassed); } private void performConcurrentOperation() { // 实现需要测试的多线程逻辑 testPassed = true; } } ``` ### 使用 GroboUtils 简化测试 GroboUtils 是一个专门用于简化多线程测试的库,它提供了 `MultiThreadedTestRunner` 类来管理多个线程的执行。例如: ```java import org.groboutils.junit.v1.MultiThreadedTestRunner; import org.groboutils.junit.v1.TestRunnable; public class GroboUtilsExampleTest extends TestCase { public void testParallelExecution() throws Throwable { TestRunnable testTask = new TestRunnable() { @Override public void runTest() throws Exception { // 执行并发测试逻辑 assertTrue(true); } }; MultiThreadedTestRunner runner = new MultiThreadedTestRunner(testTask, 5); runner.runTestRunnables(); // 启动 5 个线程并发执行 } } ``` ### 使用 `CountDownLatch` 和 `CyclicBarrier` 控制线程行为 在测试中,经常需要控制线程的启动和结束顺序。`CountDownLatch` 和 `CyclicBarrier` 是两个非常有用的同步工具。例如,`CountDownLatch` 可以确保所有线程在某个条件满足后才开始执行。 ### 模拟高并发场景 为了模拟高并发场景,可以使用线程池和任务队列来模拟大量并发请求。例如,使用 `ExecutorService` 来管理线程池: ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolTest { @Test public void testThreadPool() throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(10); CountDownLatch latch = new CountDownLatch(10); for (int i = 0; i < 10; i++) { executor.submit(() -> { try { // 执行并发任务 performTask(); } finally { latch.countDown(); } }); } latch.await(); executor.shutdown(); } private void performTask() { // 模拟任务逻辑 } } ``` ### 使用 JUnit 的超时机制 在 JUnit 中可以使用 `@Rule` 和 `Timeout` 来设置测试的最长执行时间,以防止测试挂起或死锁: ```java @Rule public Timeout globalTimeout = Timeout.seconds(10); // 所有测试最多运行 10 秒 ``` ### 测试线程安全的数据结构 当测试线程安全的数据结构时,可以使用多个线程并发地读数据,并验证最终状态是否符合预期。例如,测试 `ConcurrentHashMap` 的并发入: ```java @Test public void testConcurrentHashMap() throws InterruptedException { ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); int threadCount = 5; CountDownLatch latch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { new Thread(() -> { for (int j = 0; j < 100; j++) { map.put(Thread.currentThread().getName() + j, j); } latch.countDown(); }).start(); } latch.await(); assertEquals(threadCount * 100, map.size()); } ``` ### 使用 `Thread.sleep()` 和 `join()` 控制执行顺序 在某些情况下,可以使用 `Thread.sleep()` 或 `join()` 来等待线程完成,但这种方式可能导致测试不稳定。建议优先使用同步工具(如 `CountDownLatch`)[^1]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值