在一些单元测试时,我们有可能需要调用一些类的线程,但是,在junit原有的模型上,要么runnable对象被忽略了,要么就得调用它的run()方法,但是,这样的调用也就失去了并发性,在想要查看线程之间的调度时,这样的功能是不够的。
首先来看一段简单的代码,我们有个类来计算pi,还有个去查看即时的pi值。
- //class 'calculate pi'
- public class pi extends Thread {
- volatile double pi;
- public double getPi() {
- return this.pi;
- }
- public void setPi(double pi) {
- this.pi = pi;
- }
- public void run() {
- calPI();
- }
- private double calPI() {
- boolean negative = true;
- for (int i = 3; i < Long.MAX_VALUE; i += 2) {
- if (negative)
- pi -= (1.0 / i);
- else
- pi += (1.0 / i);
- negative = !negative;
- }
- pi += 1.0;
- pi *= 4.0;
- return this.pi;
- }
- public pi() {
- start();
- }
- }
- //class view the value of pi
- public class observer extends Thread {
- pi pi;
- observer(pi pi) throws InterruptedException {
- this.pi = pi;
- System.out.println("Start to calculate pi");
- start();
- }
- public void run() {
- while (true) {
- double zz = pi.pi;
- try {
- Thread.sleep(1000);
- System.out.println((zz + 1) * 4);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- //测试类
- import junit.framework.TestCase;
- public class observerTest extends TestCase {
- protected void setUp() throws Exception {
- }
- protected void tearDown() throws Exception {
- }
- public void testObserver() throws InterruptedException {
- pi temp = new pi();
- new observer(temp);
- }
- }
- //改写后的pi计算
- import net.sourceforge.groboutils.junit.v1.TestRunnable;
- public class testpi extends TestRunnable {
- volatile double pi;
- public double getPi() {
- return this.pi;
- }
- public void setPi(double pi) {
- this.pi = pi;
- }
- public void runTest() {
- calPI();
- }
- private double calPI() {
- boolean negative = true;
- for (int i = 3; i < Long.MAX_VALUE; i += 2) {
- if (negative)
- pi -= (1.0 / i);
- else
- pi += (1.0 / i);
- negative = !negative;
- }
- pi += 1.0;
- pi *= 4.0;
- return this.pi;
- }
- public testpi() {
- }
- }
- //改写后的ob
- import net.sourceforge.groboutils.junit.v1.TestRunnable;
- public class testob extends TestRunnable {
- testpi pi;
- testob(testpi pi) throws InterruptedException {
- this.pi = pi;
- System.out.println("Start to calculate pi");
- }
- public void runTest() {
- while (true) {
- double zz = pi.pi;
- try {
- Thread.sleep(1000);
- System.out.println((zz + 1) * 4);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- //改写后的测试类
- import net.sourceforge.groboutils.junit.v1.MultiThreadedTestRunner;
- import net.sourceforge.groboutils.junit.v1.TestRunnable;
- import junit.framework.TestCase;
- public class groboutil_test1 extends TestCase {
- public void testobserver() throws Throwable {
- TestRunnable tr1,tr2;
- tr1=new testpi();
- tr2=new testob((testpi)tr1);
- TestRunnable[] trs={tr1,tr2};
- MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(trs);
- mttr.runTestRunnables();
- }
- }
有了GroboUtils,多线程测试从此变得简单而快乐。
GroboUtils链接: http://groboutils.sourceforge.net/