JUnit4-Result.java 源代码 解读与分析

JUnit4-Result.java 源代码 解读与分析

以下是涉及到的知识点
1. 原子类
2. CopyOnWriteArrayList 写时复制
3. 序列化的控制
方式1:实现Externalizable接口(代替Serializable)–**重载**writeExternal(ObjectOutput out)方法和readExternal(ObjectInput in)方法
方式2 : 在要序列化的对象上**添加**readObject(ObjectInputStream in), writeObject(ObjectOutputStream out), readResolve等方法。

作用域

    private final AtomicInteger count;  //测试个数
    private final AtomicInteger ignoreCount;//被忽略的测试个数
    private final CopyOnWriteArrayList<Failure> failures; //测试异常
    private final AtomicLong runTime; //运行时间
    private final AtomicLong startTime; //开始时间

这里使用原子类,AtomicInteger或者AtomicLong,保证对这些变量访问时的线程安全。

//AtomicInteger 的常用方法

int addAndGet(int delta)  // 原值基础上增加delta
int decrementAndGet()  // 自减后取值
int incrementAndGet() // 自增后取值
int get() //取得当前值
int set(val) //设置指定值

//以下是先取值,然后操作
int getAndAdd(int delta)
int getAndIncrement()
int getAndDecrement()

CopyOnWriteArrayList 是一种写时复制的容器,就是容器在写时,先拷贝原数组到新数组中,在新数组中进行写入操作,最后修改引用指向新数组。在写时还是要有锁的,不过读取的时候就不需要加锁了。在多线程情况下,同步读和写,读到的还是原来的内容(引用的修改还没有完成的话)。这样也能够保证线程安全。如下是,set, add, get方法的源码

public class CopyOnWriteArrayList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    public E set(int index, E element) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            E oldValue = get(elements, index);

            if (oldValue != element) {
                int len = elements.length;
                Object[] newElements = Arrays.copyOf(elements, len);
                newElements[index] = element;
                setArray(newElements);
            } else {
                // Not quite a no-op; ensures volatile write semantics
                setArray(elements);
            }
            return oldValue;
        } finally {
            lock.unlock();
        }
    }

    public boolean add(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            Object[] newElements = Arrays.copyOf(elements, len + 1);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }

    private E get(Object[] a, int index) {
        return (E) a[index];
    }

    public E get(int index) {
        return get(getArray(), index);
    }
}

内置的监听器

Listener是Result的私有内部类, 通知者中的第一个监听器就是它,用于测试时的实时统计。
由于Listener的外围类Result的作用域是线程安全访问的,所以Listener是线程安全的,有@RunListener.ThreadSafe注解,就不用再额外封装到SynchronizedRunListener中了。

public class JUnitCore {
    public Result run(Runner runner) {
        Result result = new Result();
        RunListener listener = result.createListener();
        notifier.addFirstListener(listener);
        try {
            notifier.fireTestRunStarted(runner.getDescription());
            runner.run(notifier);
            notifier.fireTestRunFinished(result);
        } finally {
            removeListener(listener);
        }
        return result;
    }
}
    @RunListener.ThreadSafe
    private class Listener extends RunListener {
        @Override
        public void testRunStarted(Description description) throws Exception {
            startTime.set(System.currentTimeMillis());
        }

        @Override
        public void testRunFinished(Result result) throws Exception {
            long endTime = System.currentTimeMillis();
            runTime.addAndGet(endTime - startTime.get());
        }

        @Override
        public void testFinished(Description description) throws Exception {
            count.getAndIncrement();
        }

        @Override
        public void testFailure(Failure failure) throws Exception {
            failures.add(failure);
        }

        @Override
        public void testIgnored(Description description) throws Exception {
            ignoreCount.getAndIncrement();
        }

        @Override
        public void testAssumptionFailure(Failure failure) {
            // do nothing: same as passing (for 4.5; may change in 4.6)
        }
    }

序列化和反序列化还原

由于Result方法中有readObject, writeObject, readResolve方法,那么在序列化Result时, ObjectInputStream.readObject(result) 时,会自动调用result中自定义的readOjbect和readResolve方法,ObjectOutputStream.writeObject(result), 会自动调用result中的writeObject方法,进行对象的序列化。
在实现了Serializable接口的对象中,添加这几个方法,用于对序列化控制。在对象writeObject中,可以调用defaultWriteObject()来选择执行默认的writeObject()方法。同样defaultReadObject()执行默认的readObject()。这样我们可以在原先序列化的基础上进行扩展。
Result 将需要序列化的作用域引入到了私有嵌套类SerializedForm中,用于帮助Result的序列化。

public class Result implements Serializable {

    private SerializedForm serializedForm;

    private Result(SerializedForm serializedForm) {
    }

    private void writeObject(ObjectOutputStream s) throws IOException {
        SerializedForm serializedForm = new SerializedForm(this);
        serializedForm.serialize(s);
    }

    private void readObject(ObjectInputStream s)
            throws ClassNotFoundException, IOException {
        serializedForm = SerializedForm.deserialize(s);
    }

    private Object readResolve()  {
        return new Result(serializedForm);
    }

    private static class SerializedForm implements Serializable {

        public SerializedForm(Result result) {        
        }

        private SerializedForm(ObjectInputStream.GetField fields) throws IOException {
            fCount = (AtomicInteger) fields.get("fCount", null);
        }

        public void serialize(ObjectOutputStream s) throws IOException {
        }

        public static SerializedForm deserialize(ObjectInputStream s)
                throws ClassNotFoundException, IOException {
        }
    }
}

如下,是一个测试。正常情况下transient瞬时量是不会被序列化的,但是通过对序列化的控制,我们仍能够将其序列化保存。

/**
 * 序列化控制
 * 序列化 & 反序列化还原
 * @author live
 * Create on 17-8-12
 */
public class SerializedDemo implements Serializable {

    private static final long serialVersionUID = 1L;
    private final String name;
    private transient String tran;

    private SerializedForm serializedForm;

    public SerializedDemo(String name, String tran) {
        this.name = name;
        this.tran = tran;
    }

    public SerializedDemo(SerializedForm serializedForm) {
        this.name = serializedForm.name;
        this.tran = serializedForm.tran;
    }

    private void writeObject(ObjectOutputStream outputStream) throws IOException {
        System.out.println("Hello, This is in the writeObject Function.");
        SerializedForm form = new SerializedForm(this);
        form.serialize(outputStream);
    }

    private void readObject(ObjectInputStream inputStream) throws ClassNotFoundException, IOException {
        System.out.println("Hello, This is in the readObject Function.");
        serializedForm = SerializedForm.deserialize(inputStream);
    }

    private Object readResolve() {
        System.out.println("This is in the readResolve Function.");
        return new SerializedDemo(serializedForm);
    }

    @Override
    public String toString() {
        return String.format("{name:%s, tran:%s}", name, tran);
    }

    private static class SerializedForm implements Serializable {
        private final String name;
        private final String tran;

        public SerializedForm(SerializedDemo demo) {
            this.name = demo.name;
            this.tran = demo.tran;
        }

        public SerializedForm(ObjectInputStream inputStream) throws ClassNotFoundException, IOException{
            ObjectInputStream.GetField fields = inputStream.readFields();
            name = (String) fields.get("name", "null");
            //tran = (String) fields.get("tran", "null");
            tran =  (String)inputStream.readObject();
        }

        public void serialize(ObjectOutputStream outputStream) throws IOException {
            ObjectOutputStream.PutField fields = outputStream.putFields();
            fields.put("name", this.name);

            outputStream.writeFields();
            //fields.put("tran", this.tran);
            outputStream.writeObject(tran);
        }

        public static SerializedForm deserialize(ObjectInputStream inputStream) throws ClassNotFoundException, IOException {
            return new SerializedForm(inputStream);
        }
    }

    public static void main(String[] args) throws ClassNotFoundException, IOException {
        final String fileName = "SerializedDemo.out";

        SerializedDemo serializedDemo = new SerializedDemo("序列化与反序列化还原", "瞬时量");

        ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
        outputStream.writeObject(serializedDemo);
        outputStream.close();

        ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(fileName));
        SerializedDemo deSerializedDemo = (SerializedDemo) inputStream.readObject();
        //
        System.out.println(serializedDemo);
        System.out.println(deSerializedDemo);

    }
}

序列化

完整代码

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.ObjectStreamField;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

/**
 * A <code>Result</code> collects and summarizes information from running multiple tests.
 * All tests are counted -- additional information is collected from tests that fail.
 *
 * @since 4.0
 */

public class Result implements Serializable {
    private static final long serialVersionUID = 1L;
    private static final ObjectStreamField[] serialPersistentFields =
            ObjectStreamClass.lookup(SerializedForm.class).getFields();
    private final AtomicInteger count;
    private final AtomicInteger ignoreCount;
    private final CopyOnWriteArrayList<Failure> failures;
    private final AtomicLong runTime;
    private final AtomicLong startTime;

    /** Only set during deserialization process. */
    private SerializedForm serializedForm;

    public Result() {
        count = new AtomicInteger();
        ignoreCount = new AtomicInteger();
        failures = new CopyOnWriteArrayList<Failure>();
        runTime = new AtomicLong();
        startTime = new AtomicLong();
    }

    private Result(SerializedForm serializedForm) {
        count = serializedForm.fCount;
        ignoreCount = serializedForm.fIgnoreCount;
        failures = new CopyOnWriteArrayList<Failure>(serializedForm.fFailures);
        runTime = new AtomicLong(serializedForm.fRunTime);
        startTime = new AtomicLong(serializedForm.fStartTime);
    }

    /**
     * @return the number of tests run
     */
    public int getRunCount() {
        return count.get();
    }

    /**
     * @return the number of tests that failed during the run
     */
    public int getFailureCount() {
        return failures.size();
    }

    /**
     * @return the number of milliseconds it took to run the entire suite to run
     */
    public long getRunTime() {
        return runTime.get();
    }

    /**
     * @return the {@link Failure}s describing tests that failed and the problems they encountered
     */
    public List<Failure> getFailures() {
        return failures;
    }

    /**
     * @return the number of tests ignored during the run
     */
    public int getIgnoreCount() {
        return ignoreCount.get();
    }

    /**
     * @return <code>true</code> if all tests succeeded
     */
    public boolean wasSuccessful() {
        return getFailureCount() == 0;
    }

    private void writeObject(ObjectOutputStream s) throws IOException {
        SerializedForm serializedForm = new SerializedForm(this);
        serializedForm.serialize(s);
    }

    private void readObject(ObjectInputStream s)
            throws ClassNotFoundException, IOException {
        serializedForm = SerializedForm.deserialize(s);
    }

    private Object readResolve()  {
        return new Result(serializedForm);
    }

    @RunListener.ThreadSafe
    private class Listener extends RunListener {
        @Override
        public void testRunStarted(Description description) throws Exception {
            startTime.set(System.currentTimeMillis());
        }

        @Override
        public void testRunFinished(Result result) throws Exception {
            long endTime = System.currentTimeMillis();
            runTime.addAndGet(endTime - startTime.get());
        }

        @Override
        public void testFinished(Description description) throws Exception {
            count.getAndIncrement();
        }

        @Override
        public void testFailure(Failure failure) throws Exception {
            failures.add(failure);
        }

        @Override
        public void testIgnored(Description description) throws Exception {
            ignoreCount.getAndIncrement();
        }

        @Override
        public void testAssumptionFailure(Failure failure) {
            // do nothing: same as passing (for 4.5; may change in 4.6)
        }
    }

    /**
     * Internal use only.
     */
    public RunListener createListener() {
        return new Listener();
    }

    /**
     * Represents the serialized output of {@code Result}. The fields on this
     * class match the files that {@code Result} had in JUnit 4.11.
     */
    private static class SerializedForm implements Serializable {
        private static final long serialVersionUID = 1L;
        private final AtomicInteger fCount;
        private final AtomicInteger fIgnoreCount;
        private final List<Failure> fFailures;
        private final long fRunTime;
        private final long fStartTime;

        public SerializedForm(Result result) {
            fCount = result.count;
            fIgnoreCount = result.ignoreCount;
            fFailures = Collections.synchronizedList(new ArrayList<Failure>(result.failures));
            fRunTime = result.runTime.longValue();
            fStartTime = result.startTime.longValue();
        }

        @SuppressWarnings("unchecked")
        private SerializedForm(ObjectInputStream.GetField fields) throws IOException {
            fCount = (AtomicInteger) fields.get("fCount", null);
            fIgnoreCount = (AtomicInteger) fields.get("fIgnoreCount", null);
            fFailures = (List<Failure>) fields.get("fFailures", null);
            fRunTime = fields.get("fRunTime", 0L);
            fStartTime = fields.get("fStartTime", 0L);
        }

        public void serialize(ObjectOutputStream s) throws IOException {
            ObjectOutputStream.PutField fields = s.putFields();
            fields.put("fCount", fCount);
            fields.put("fIgnoreCount", fIgnoreCount);
            fields.put("fFailures", fFailures);
            fields.put("fRunTime", fRunTime);
            fields.put("fStartTime", fStartTime);
            s.writeFields();
        }

        public static SerializedForm deserialize(ObjectInputStream s)
                throws ClassNotFoundException, IOException {
            ObjectInputStream.GetField fields = s.readFields();
            return new SerializedForm(fields);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值