Last active
March 4, 2017 20:37
-
-
Save jayv/663eb566c7b6bda4bc87c06cf9f671d3 to your computer and use it in GitHub Desktop.
Mocking CDI Events doesn't work out of the box with ScalaMock, extend from the MockEventFactory and create an Event[T] using mockEvent[T]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import MockEventFactory | |
import javax.enterprise.event.Event | |
import org.junit.runner.RunWith | |
import org.scalamock.scalatest.MockFactory | |
import org.scalatest.junit.JUnitRunner | |
import org.scalatest.FlatSpec | |
@RunWith(classOf[JUnitRunner]) | |
class ExampleSpec extends FlatSpec with MockFactory with MockEventFactory { | |
case class ExampleEvent() | |
class Example(emitter:Event[ExampleEvent]) { | |
def send() = emitter.fire(ExampleEvent()) | |
} | |
"Example" should "fire a single ExampleEvent when send() is called" in { | |
val emitter = mockEvent[ExampleEvent] | |
emitter.mockFire.expects(ExampleEvent()).once | |
new Example(emitter).send() | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.annotation.Annotation | |
import javax.enterprise.event.Event | |
import javax.enterprise.util.TypeLiteral | |
import org.scalamock.function.MockFunction1 | |
import org.scalamock.util.Defaultable | |
/** | |
* Factory for Mocked CDI Event emitters, scala-mock can't mock Event[T] due to TypeLiteral. | |
* Extend `MockEventFactory` and define mock with this:<br> | |
* `val em = mockEvent[MyEventType]`<br> | |
* example expectation: `em.mockFire.expect(MyEventType()).once()` <br> | |
*/ | |
trait MockEventFactory extends MockFunction1Like { | |
def mockEvent[T]: MockEvent[T] = new MockEvent[T]{ | |
override val mockFire = mockFunction[T, Unit] | |
} | |
} | |
/** | |
* Partially implemented Event[T] with only `fire(T)` replaced by a `mockFunction`. | |
* @tparam T event Type | |
*/ | |
trait MockEvent[T] extends Event[T] { | |
val mockFire: MockFunction1[T, Unit] | |
override def fire(event: T): Unit = mockFire(event) | |
override def select(qualifiers: Annotation*): Event[T] = ??? | |
override def select[U <: T](subtype: Class[U], qualifiers: Annotation*): Event[U] = ??? | |
override def select[U <: T](subtype: TypeLiteral[U], qualifiers: Annotation*): Event[U] = ??? | |
} | |
/** | |
* Mixin that matches `mockFunction[T,R]` from scala-mock `MockFactory`. | |
*/ | |
trait MockFunction1Like { | |
protected def mockFunction[T1, R: Defaultable]: MockFunction1[T1, R] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment