Junit本身是不支持普通的多线程测试的,这是因为Junit的底层实现上,是用System.exit退出用例执行的。JVM都终止了,在测试线程启动的其他线程自然也无法执行。所以要想编写多线程Junit测试用例,就必须让主线程等待所有子线程执行完成后再退出。想到的办法自然是Thread中的join方法。使用GroboUtils这个Junit多线程测试的开源的第三方的工具包。
GroboUtils官网如下:http://groboutils.sourceforge.net/
下载页面:http://groboutils.sourceforge.net/downloads.html,解压后 使用 GroboUtils-5
依赖
<dependency><groupId>net.sourceforge.groboutils</groupId>
<artifactId>groboutils-core</artifactId>
<version>5</version>
</dependency>
代码如下:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration@ContextConfiguration(locations = { "classpath*:beans*.xml", "classpath:spring-mvc.xml" })//加载配置文件
public class TransFlightExcelTest {
private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(TransFlightExcelTest.class);
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
// this.mockMvc = MockMvcBuilders.standaloneSetup(new
// TransferFlightRealController(),transferFlightRealService).build();
}
/**
* 多线程并发测试
*
* @throws Exception
*/
@Test
public void transFlightExportExcel() throws Exception {
long start = System.currentTimeMillis();
int runnerCount = 5;
// Rnner数组,想当于并发多少个。
TestRunnable[] trs = new TestRunnable[runnerCount];
for (int i = 0; i < runnerCount; i++) {
trs[i] = new MyThread();
}
// 用于执行多线程测试用例的Runner,将前面定义的单个Runner组成的数组传入
MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(trs);
try {
// 开发并发执行数组里定义的内容
mttr.runTestRunnables();
} catch (Throwable e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
LOGGER.info("[{}个同时导出中转航班Excel耗时{}毫秒]", runnerCount, (end - start));
}
private class MyThread extends TestRunnable{
@Override
public void runTest() throws Throwable {
//测试的业务逻辑
flightExcelContent();}
}
//mockMvc相关代码
private void flightExcelContent() throws Exception {MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/flight/real/flightExcel.do")
.param("inTimeRange", "").param("flightDirection", "inToOut").param("department", "")
.param("destination", "").param("flightno", "").param("inCarriers", "").param("outCarriers", "")
.param("outTimeRange", "").param("transferTime", "").param("transferType", "")
.accept(MediaType.APPLICATION_OCTET_STREAM)).andExpect(status().isOk()).andReturn();
MockHttpServletResponse mhsr = mvcResult.getResponse();
byte bs[] = mhsr.getContentAsByteArray();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date d = new Date();
String time = sdf.format(d);
FileOutputStream fos = new FileOutputStream("E:/temp/中转航班" + time + ".xlsx");
fos.write(bs);
fos.close();
}
}