Skip to content

Instantly share code, notes, and snippets.

@samhendley
Created April 14, 2010 21:29
Show Gist options
  • Save samhendley/366364 to your computer and use it in GitHub Desktop.
Save samhendley/366364 to your computer and use it in GitHub Desktop.
package org.psi
class UnConstructableClass{
dontExcept
def dontExcept() { b.size}
val b = List()
}
class DerivedClass(delayCall : Boolean) extends BaseClass(delayCall)
{
start
val b = List()
def act() : Int = {b.size}
}
class DerivedClassB(delayCall : Boolean) extends BaseClass(delayCall)
{
val b = List()
start
def act() : Int = {b.size}
}
abstract class BaseClass(delayCall: Boolean){
implicit def asRunnable(func : ()=>unit) : Runnable = {new Runnable(){def run(){func()}}}
def act() : Int // abstract or overriden function
var result : Int = -1;
def start(){
if(delayCall) {
var t = new Thread(() => {
try{
result = act()
}catch{
case n : NullPointerException =>
result = -2;
}
})
val r = new Random
t.start
if(r.nextBoolean())Thread.sleep(10)
}
else result = act()
}
}
import org.scalatest.FunSuite
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
@RunWith(classOf[JUnitRunner])
class ConstuctorIssues extends FunSuite with ShouldMatchers{
/// This test shows that the startup/teardown behavior is working without crashing
test("Unconstrucable Class") {
intercept[NullPointerException]{
new UnConstructableClass
}
}
test("Unconstructable Derived Class") {
intercept[NullPointerException]{
new DerivedClass(false)
}
}
test("raceCondition Derived Class"){
// this fails on my machine around 50% of the time, you might have to play with the timing
// to make it fail on you machine (or removed the random sleep) since it is a race condtion
val b = new DerivedClass(true)
Thread.sleep(3)
b.result should equal(0)
}
test("Valid Derived Class") {
new DerivedClassB(false)
}
test("Valid Derived Class immune to race conditions."){
val b = new DerivedClassB(true)
Thread.sleep(3)
b.result should equal(0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment