问题: 在junit的单元测试中,用thread创建多个线程时,单元测试并不会等待主线程下启动的新线程是否执行结束,只要主线程结束完成,单元测试就会关闭,导致主线程中启动的新线程不能顺利执行完!
简单的解决办法: 在主线程中sleep,等待子线程的结束!
部分示例代码
package TestRedis;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.esoft.invest.service.AutoInvestJobService;
import Test.MyThread;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:application-context.xml")
public class TestRedis {
@Autowired
private AutoInvestJobService autoInvestJobService;
//多线程测试并发
@Test
public void testThread() {
try {
System.out.println("test当前线程:" + Thread.currentThread().getName());
for (int i = 0; i < 5; i++) {
Thread.sleep(200);
long id = 20180625000003l;
String loanId = Long.toString(id+i);
Thread t = new MyThread(this.autoInvestJobService,loanId);
t.start();
}
// junit单元测试并不支持多线程,所以要想测试多线程时,在主线程中等待,以确保子线程能够执行完.
Thread.sleep(520000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package Test;
import com.esoft.invest.service.AutoInvestJobService;
import com.esoft.invest.service.InvestService;
/**
* 类说明
*
* @author lv617
* @date 2018年5月24日 上午9:59:51
*/
public class MyThread extends Thread {
private InvestService investService;
private AutoInvestJobService autoInvestJobService;
private String loanId;
//构造方法传参
public MyThread(AutoInvestJobService autoInvestJobService) {
this.autoInvestJobService = autoInvestJobService;
}
//构造方法传参
public MyThread(AutoInvestJobService autoInvestJobService, String loanId) {
this.autoInvestJobService = autoInvestJobService;
this.loanId = loanId;
}
//构造方法传参
public MyThread(InvestService investService) {
this.investService = investService;
}
@Override
public void run(){
System.err.println("新线程:" + Thread.currentThread().getName() + "----start----");
// TODO
this.autoInvestJobService.executeAutoInvest(this.loanId, true, "true", "all");
System.err.println("新线程:" + Thread.currentThread().getName() + "----end----");
}
}