junit中测试完成后会进行jvm退出,而不是线程退出,所以任一线程退出都会导致测试结束,junit想进行多线程测试需要进行另外包装,网上看到一个投机取巧的例子还不错,贴上我的测试代码(代码中我需要测试socket客户端代码,所以需要模拟服务端才能测试,故而进行两个线程测试):
package com.newland.sri.utap.ats; import com.newland.sri.utap.ats.utils.AnalyPacket; import com.newland.sri.utap.utils.Constants; import org.apache.ignite.Ignition; import org.junit.Before; import org.junit.Test; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.ServerSocket; import java.net.Socket; /** * 测试 * Created by garfield on 2016/6/20. */ public class AtsTest { final static private long THREAD_MAX_RUNTIME = 10000000; final static private long THREAD_WAITTIME = 200; private T1 myThread1 = null; private T2 myThread2 = null; @Before public void setUp() throws Exception { myThread1 = new T1(); myThread2 = new T2(); } @Test(timeout = THREAD_MAX_RUNTIME) public void testRun() throws Exception { Thread t1 = new Thread(myThread1); Thread t2 = new Thread(myThread2); t1.start(); t2.start(); Thread tc = Thread.currentThread(); synchronized (tc) { while (t1.isAlive() || t2.isAlive()) { tc.wait(THREAD_WAITTIME); } tc.notify(); } } class T1 implements Runnable { private ServerSocket server; @Override public void run() { try { server = new ServerSocket(6666); Constants.IGNITE = Ignition.start("utap-ats.xml"); while (true) { AgentServer agentServer = new AgentServer(); agentServer.start(); break; } } catch (Exception e) { e.printStackTrace(); } } } class T2 implements Runnable { @Override public void run() { try { Socket socket = new Socket("127.0.0.1", 6666); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.write();//写入东西,此处代码省略 out.flush(); while (true) { if (socket.getInputStream() != null) { DataInputStream in = new DataInputStream(socket.getInputStream()); byte[] bytes = new byte[200]; int start = 0; in.read(bytes); break; } } } catch (Exception e) { e.printStackTrace(); } } } }
可以看到我的线程是启动了ignite了的,并且有服务端和客户端,这些都不重要= =,代码中
Thread tc = Thread.currentThread(); synchronized (tc) { while (t1.isAlive() || t2.isAlive()) { tc.wait(THREAD_WAITTIME); } tc.notify(); }
这一段使得线程切换得以进行,通过这个方法,很多多线程的单元测试都可以进行啦.