I have a simple function like :
object Actions {
def myAction() {
//do some stuff
}
}
Is there a way to use this method as a scenario ? Like :
val scn = scenario("My scenario").exec(Actions.myAction())
This code doesn't compile but I don't understand why.. it seams exec is waiting for a chain / scenario builder (or a validation object).
Thks !
Yes, exec expects a ChainBuilder, but here, you're returning nothing (Scala deprecated procedure style) because you're missing the = sign.
object Actions {
def myAction() = {
//do some stuff
}
}
Related
I have the following code:
class MyClass {
def someMethods(): Unit = {
val result1 = method1()
val result2 = method2(result)
}
}
No I want to test if method1 and method2 are called, when I run someMethod.
class TestMyClass {
#Test
def testSomeMethods(): Unit = {
val myClass = new MyClass()
val myClassSpy = Mockito.spy(myClass)
myClassSpy.someMethods()
verify(myClassSpy).method1()
}
}
For method1 this is working, but method2 needs a parameter, that is provided by method1.
Can I not just do something like assertTrue(method2.called)?
Because I do not want to check the result of the methods, I just want to know if they were called.
Hmm, using a spy for that is already a smell, you shouldn't be testing internals of your class like that.
In any case you could do Mockito.verify(myClassSpy).method2(Mockito.any()) and that would do the trick, but I'd seriously review your design and the motivation behind this test as it really feels like the wrong approach.
I have a test suite that implements BeforeAndAfter, and I'd ideally like to be able to check in my after() method if the test failed, and if it did calculate some value and print it out. Is there an inbuilt way of doing this?
ps. I know I can do a try/catch around the whole test but I'd rather not have to do that.
I don't think you can do it in after(), however you can do it by overriding withFixture(). This method runs the actual test, after that you can match the result and print something in case of failure:
class ExampleSpec extends WordSpec with MustMatchers {
"Example" must {
"work correctly" in {
3 must be(3)
}
"not fail" in {
true must be(false)
}
}
override def withFixture(test: NoArgTest) = super.withFixture(test) match {
case failed: Failed =>
val nameLen = test.name.length
info(s"The test '${test.name}' failed")
info(s"The test name is $nameLen characters long")
failed
case other => other
}
}
See Sharing Fixtures, especially the section "Overriding withFixture(NoArgTest)"
Depending on your needs, you can:
1) write something like def around[T](code: => T) = try {code} ... and use it like:
test("mytest") {
around {
}
}
it should "blabla" in around {
...
}
2) If you don't use specs then just write your own:
def mytest[T](name: String)(code: =>T) = test(name){
try {
code
} ...
}
or just override test:
override def test[T](name: String)(code: =>T) = super.test(name){
try {
code
} ...
}
Both can be done in separate trait, btw.
3) Override withFixture as it described #alextsc's answer
4) Write your own reporter if you want to intercept all tests in your build
P.S. BeforeAndAfter/withFixture are meant to clean up resources (that's why they don't give you any access to exception), so logically reporter solution might fit better if you need to analyze and rerepresent your errors, but it's not much convenient.
For whatever reason Mocktio will not mock a method I have in a trait, it will call the actual method. Here is my test:
"displays the index page" in {
val mockAuth = mock[AuthMethods]
when(mockAuth.isAllowed(-1, "", "")).thenReturn(true)
val controller = new TestController()
val result = controller.index().apply(FakeRequest())
val bodyText = contentAsString(result)
bodyText must include ("Name")
}
Here is the trait and object:
trait AuthMethods {
def isAllowed(userID:Long, method:String, controller:String) : Boolean = {
//do stuff..
}
object Authorized extends AuthMethods with ActionBuilder [Request] {
def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
if(isAllowed(userID, method, controller) {
//do some more stuff..
}
Any thoughts on why its calling the actual method verses the mocked method? I am using Scala 2.10.4. Any help would be appreciated.
I forgot to mention, Authorized is a Action Composition and here is how it is being used:
def index = Authorized {
Ok(html.Stations.index(Stations.retrieveAllStations))
}
You have created a mock implementation mockAuth but have not done anything with it. Creating a mock implementation will not magically cause it to replace some other object. It looks like you want to create a mock of the Authorized object and arrange for your TestController to use it. You'll probably have to break a dependency somewhere.
(updated) Since this is in the context of the Play framework, you might find this blog post helpful. It describes a situation similar to yours. It appears you will have to change the way the Authorized object is referenced in order to supply a mock implementation.
I've been searching for a while and can't seem to find something that matches exactly what I need.
I want to have a way to wrap any class (let's say T) with something that would "do something cool" before and after each invocation of the public methods of this T class, and this thing would look like T to the compiler.
Here's some pseudo code to illustrate:
object CoolWrap {
def apply[T](underlying: T) {
new CoolWrapImpl(underlying).asInstanceOf[T]
}
}
class CoolWrapImpl[T](underlying: T) extends T {
def onPublicMethod(method: Method, params: Params) = {
// method would be the method that was invoked on T
doSomethingCool1(params) // like logging
val resp = measureTime { method.invoke(params) }
doAnotherCoolThing()
resp
}
}
Using reflection is not out of the question, this would only happen once per instance that would live in memory throughout the life of the process, so I'm not concerned with it being slow to instantiate.
Is this even possible? (currently forced to use Scala 2.9.2)
Thanks!
I'm using the Netty library (version 4 from GitHub). It works great in Scala, but I am hoping for my library to be able to use continuation passing style for the asynchronous waiting.
Traditionally with Netty you would do something like this (an example asynchronous connect operation):
//client is a ClientBootstrap
val future:ChannelFuture = client.connect(remoteAddr);
future.addListener(new ChannelFutureListener {
def operationComplete (f:ChannelFuture) = {
//here goes the code that happens when the connection is made
}
})
If you are implementing a library (which I am) then you basically have three simple options to allow the user of the library to do stuff after the connection is made:
Just return the ChannelFuture from your connect method and let the user deal with it - this doesn't provide much abstraction from netty.
Take a ChannelFutureListener as a parameter of your connect method and add it as a listener to the ChannelFuture.
Take a callback function object as a parameter of your connect method and call that from within the ChannelFutureListener that you create (this would make for a callback-driven style somewhat like node.js)
What I am trying to do is a fourth option; I didn't include it in the count above because it is not simple.
I want to use scala delimited continuations to make the use of the library be somewhat like a blocking library, but it will be nonblocking behind the scenes:
class MyLibraryClient {
def connect(remoteAddr:SocketAddress) = {
shift { retrn: (Unit => Unit) => {
val future:ChannelFuture = client.connect(remoteAddr);
future.addListener(new ChannelFutureListener {
def operationComplete(f:ChannelFuture) = {
retrn();
}
});
}
}
}
}
Imagine other read/write operations being implemented in the same fashion. The goal of this being that the user's code can look more like this:
reset {
val conn = new MyLibraryClient();
conn.connect(new InetSocketAddress("127.0.0.1", 1337));
println("This will happen after the connection is finished");
}
In other words, the program will look like a simple blocking-style program but behind the scenes there won't be any blocking or threading.
The trouble I'm running into is that I don't fully understand how the typing of delimited continuations work. When I try to implement it in the above way, the compiler complains that my operationComplete implementation actually returns Unit #scala.util.continuations.cpsParam[Unit,Unit => Unit] instead of Unit. I get that there is sort of a "gotcha" in scala's CPS in that you must annotate a shift method's return type with #suspendable, which gets passed up the call stack until the reset, but there doesn't seem to be any way to reconcile that with a pre-existing Java library that has no concept of delimited continuations.
I feel like there really must be a way around this - if Swarm can serialize continuations and jam them over the network to be computed elsewhere, then it must be possible to simply call a continuation from a pre-existing Java class. But I can't figure out how it can be done. Would I have to rewrite entire parts of netty in Scala in order to make this happen?
I found this explanation of Scala's continuations extremely helpful when I started out. In particular pay attention to the parts where he explains shift[A, B, C] and reset[B, C]. Adding a dummy null as the last statement of operationComplete should help.
Btw, you need to invoke retrn() inside another reset if it may have a shift nested inside it.
Edit: Here is a working example
import scala.util.continuations._
import java.util.concurrent.Executors
object Test {
val execService = Executors.newFixedThreadPool(2)
def main(args: Array[String]): Unit = {
reset {
val conn = new MyLibraryClient();
conn.connect("127.0.0.1");
println("This will happen after the connection is finished");
}
println("Outside reset");
}
}
class ChannelFuture {
def addListener(listener: ChannelFutureListener): Unit = {
val future = this
Test.execService.submit(new Runnable {
def run(): Unit = {
listener.operationComplete(future)
}
})
}
}
trait ChannelFutureListener {
def operationComplete(f: ChannelFuture): Unit
}
class MyLibraryClient {
def connect(remoteAddr: String): Unit#cps[Unit] = {
shift {
retrn: (Unit => Unit) => {
val future: ChannelFuture = new ChannelFuture()
future.addListener(new ChannelFutureListener {
def operationComplete(f: ChannelFuture): Unit = {
println("operationComplete starts")
retrn();
null
}
});
}
}
}
}
with a possible output:
Outside reset
operationComplete starts
This will happen after the connection is finished