1 package com.xtremelabs.robolectric.bytecode; 2 3 import org.junit.Assert; 4 import org.junit.Test; 5 6 public class ClassCacheTest { 7 8 9 @Test 10 public void fixForCorberturaAndSonarCodeCoverage() throws InterruptedException { 11 final ClassCache classCache = new ClassCache("target/test.txt", AndroidTranslator.CACHE_VERSION); 12 13 // Substitute this LOCK with your monitor (could be you object you are 14 // testing etc.) 15 Thread locker = new Thread() { 16 @Override 17 public void run() { 18 synchronized (classCache) { 19 try { 20 Thread.sleep(Long.MAX_VALUE); 21 } catch (InterruptedException e) { 22 return; 23 } 24 } 25 } 26 }; 27 28 locker.start(); 29 30 TestThreadIsWriting attempt = new TestThreadIsWriting(classCache); 31 32 try { 33 int timeToWait = 500; 34 locker.join(timeToWait, 0); 35 36 attempt.start(); 37 long before = System.currentTimeMillis(); 38 attempt.join(timeToWait, 0); 39 long after = System.currentTimeMillis(); 40 Assert.assertEquals(false, attempt.ready); 41 Assert.assertEquals(1, (after - before) / timeToWait); 42 locker.interrupt(); 43 } finally { 44 45 } 46 } 47 48 @Test 49 public void fixForCorberturaAndSonarCodeCoverageTheOtherWayAround() throws InterruptedException { 50 final ClassCache classCache = new ClassCache("target/test.txt", AndroidTranslator.CACHE_VERSION); 51 52 // Substitute this LOCK with your monitor (could be you object you are 53 // testing etc.) 54 Thread locker = new Thread() { 55 @Override 56 public void run() { 57 synchronized (classCache) { 58 try { 59 Thread.sleep(Long.MAX_VALUE); 60 } catch (InterruptedException e) { 61 return; 62 } 63 } 64 } 65 }; 66 67 locker.start(); 68 69 TestThreadSaveAllClassesToCache attempt = new TestThreadSaveAllClassesToCache(classCache); 70 71 try { 72 int timeToWait = 500; 73 locker.join(timeToWait, 0); 74 75 attempt.start(); 76 long before = System.currentTimeMillis(); 77 attempt.join(timeToWait, 0); 78 long after = System.currentTimeMillis(); 79 Assert.assertEquals(false, attempt.ready); 80 Assert.assertEquals(1, (after - before) / timeToWait); 81 locker.interrupt(); 82 83 } finally { 84 85 } 86 } 87 88 class TestThreadIsWriting extends Thread { 89 public boolean ready = false; 90 final ClassCache classCache; 91 92 93 public TestThreadIsWriting(ClassCache classCache) { 94 super(); 95 this.classCache = classCache; 96 } 97 98 99 @Override 100 public void run() { 101 classCache.isWriting(); 102 ready = true; 103 } 104 }; 105 106 class TestThreadSaveAllClassesToCache extends Thread { 107 public boolean ready = false; 108 final ClassCache classCache; 109 110 111 public TestThreadSaveAllClassesToCache(ClassCache classCache) { 112 super(); 113 this.classCache = classCache; 114 } 115 116 117 @Override 118 public void run() { 119 classCache.saveAllClassesToCache(null, null); 120 ready = true; 121 } 122 }; 123 124 } 125