Here's an example:
trait Sender {
def send(String msg){
// do something
}
}
class Service implements Sender {
def myMethod1(){
send('Foo')
myMethod2()
}
def myMethod2(){
}
}
I am trying to test the Service class. However, I would like to stub/mock the calls to the methods provided by the trait (send)?
I have tried several different ways to stub/mock the method send, with no success:
// 1
Service.metaclass.send = { String s -> // do nothing }
// 2
def service = new MyService()
service.metaClass.send = { String s -> // do nothing }
// 3
StubFor serviceStub = new StubFor(Service.class)
serviceStub.demand.send { String s -> // do nothing }
//
trait MockedSender {
def send(String msg) { // do nothing }
}
def service = new Service() as MockedSender
These are just some of the things I tried. I even tried using Mock frameworks like Mockito. Unfortunately, nothing seems to work. Any suggestions???
Try using Spy from Spock framework!
Like this:
trait Sender {
def send(String msg){
println msg
}
}
class Service implements Sender {
def myMethod1(){
send('Foo')
myMethod2()
}
def myMethod2(){
println 'real implementation'
}
}
class UnitTest extends Specification {
def "Testing spy on real object"() {
given:
Service service = Spy(Service)
when:
service.myMethod1()
then: "service.send('Foo') should be called once and should print 'mocked' and 'real implementation' on console"
1 * service.send('Foo') >> { println 'mocked' }
}
}
Related
I´ve been looking for a suitable solution or best practice when I want to use Kotlin Flows with ordinary callbacks. My use case is that I write a kotlin library that uses Kotlin Flow internally and i have to assume that the users will use Java for instance. So I thought that the best solution is to overload a basic callback interface to my flow method and call it in collect something like this:
class KotlinClass {
interface Callback {
fun onResult(result: Int)
}
private fun foo() = flow {
for (i in 1..3) {
emit(i)
}
}
fun bar(callback: Callback) {
runBlocking {
foo().collect { callback.onResult(it) }
}
}
private fun main() {
bar(object : Callback {
override fun onResult(result: Int) {
TODO("Not yet implemented")
}
})
}
and in my Java Application i can simply use it like that:
public class JavaClass {
public void main() {
KotlinClass libraryClass = new KotlinClass();
libraryClass.bar(new KotlinClass.Callback() {
#Override
public void onResult(int result) {
// TODO("Not yet implemented")
}
});
}
}
I am not sure whats the way to go because I would like to have my Kotlin library that uses Flows usable in a good fashion for Java and Kotlin.
I came across callbackFlow but that seems to be only if I want to let´s call it flow-ify a callback-based API? Because I am quite new to Kotlin and Flows please apologise if my question is flawed in cause of missing some basic concepts of kotlin.
I would give the Java client more control over the flow. I would add a onStart and onCompletion method to your callback interface. Beside this I would use an own CoroutineScope - maybe customizable from the Java client. And I would not block the calling thread from within the Kotlin function - no runBlocking.
#InternalCoroutinesApi
class KotlinClass {
val coroutineScope = CoroutineScope(Dispatchers.Default)
interface FlowCallback {
#JvmDefault
fun onStart() = Unit
#JvmDefault
fun onCompletion(thr: Throwable?) = Unit
fun onResult(result: Int)
}
private fun foo() = flow {
for (i in 1..3) {
emit(i)
}
}
fun bar(flowCallback: FlowCallback) {
coroutineScope.launch {
foo().onStart { flowCallback.onStart() }
.onCompletion { flowCallback.onCompletion(it) }
.collect { flowCallback.onResult(it) }
}
}
fun close() {
coroutineScope.cancel()
}
}
Now the Java client is in full control how to start, collect and cancel the flow. For example you could use a latch to wait for completion, set an timeout and cancel the couroutine scope. This looks in the first place like a lot of code, but typically you will need this kind of flexibility.
public class JavaClass {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
KotlinClass libraryClass = new KotlinClass();
libraryClass.bar(new KotlinClass.FlowCallback() {
#Override
public void onCompletion(#Nullable Throwable thr) {
latch.countDown();
}
#Override
public void onResult(int result) {
System.out.println(result);
}
});
try {
latch.await(5, TimeUnit.SECONDS);
} finally {
libraryClass.close();
}
}
}
You don't need to create a interface in the Kotlin code. You can define bar like that:
fun bar(callback: (Int) -> Unit) {
runBlocking {
foo().collect { callback(it) }
}
}
From the Java code you can call the function like that:
public class JavaClass {
public static void main(String[] args) {
KotlinClass libraryClass = new KotlinClass();
libraryClass.bar(v -> { System.out.println(v); return Unit.INSTANCE; });
}
}
In case anyone wondering for a general solution. Here's our version of enhancement from #rene answer here.
Accept a generic type
A configurable coroutineScope
// JavaFlow.kt
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
#InternalCoroutinesApi
class JavaFlow<T>(
private val coroutineScope: CoroutineScope = CoroutineScope(Dispatchers.Default)
) {
interface OperatorCallback <T> {
#JvmDefault
fun onStart() = Unit
#JvmDefault
fun onCompletion(thr: Throwable?) = Unit
fun onResult(result: T)
}
fun collect(
flow: Flow<T>,
operatorCallback: OperatorCallback<T>,
) {
coroutineScope.launch {
flow
.onStart { operatorCallback.onStart() }
.onCompletion { operatorCallback.onCompletion(it) }
.collect { operatorCallback.onResult(it) }
}
}
fun close() {
coroutineScope.cancel()
}
}
Java caller-side:
// code omitted...
new JavaFlow<File>().collect(
// compressImageAsFlow is our actual kotlin flow extension
FileUtils.compressImageAsFlow(file, activity),
new JavaFlow.OperatorCallback<File>() {
#Override
public void onResult(File result) {
// do something with the result here
SafeSingleton.setFile(result);
}
}
);
// or using lambda with method references
// new JavaFlow<File>().collect(
// FileUtils.compressImageAsFlow(file, activity),
// SafeSingleton::setFile
// );
// Change coroutineScope to Main
// new JavaFlow<File>(CoroutineScopeKt.MainScope()).collect(
// FileUtils.compressImageAsFlow(file, activity),
// SafeSingleton::setFile
// );
OperatorCallback.onStart and OperatorCallback.onCompletion is optional, override it as needed.
i trying create stub or mock for CompletableFuture in spock. My method is called async and return CompletableFuture. In spock method always return null. What's wrong?
public class ProductFactory() {
#Autowired
ProductRepository repository;
public Product create(String name) {
this.checkProductExists(name);
}
public CompletableFuture<Boolean> checkProductExists(String name) {
//call repository and return
boolean result = this.repository.checkProductExists(name);
return CompletableFuture.completedFuture(result)
}
}
class ProductFactorySpec extends Specification {
ProductRepository repository = Mock(ProductRepository)
ProductFactory factory = new ProductFactory(repository)
def "When i decide create new product"() {
def future = CompletableFuture.completedFuture(true)
when:
repository.checkProductExists("Fake string") >> future
future.get() >> true
def result = this.factory.create(fakeOfferData())
then:
result instanceof Product
}
}
Update code, it's was not completed.
items.checkProductExists("Fake string") >> future: items is not defined, did you mean factory?
boolean result = this.repository.checkProductExists(name); this line doesn't expect a future, so why are you trying to return one
future.get() >> true you created a real CompletableFuture so stubbing is not possible
All stubbing should be performed outside of the when block in the given/setup block
Your create doesn't return a Product
From the code you have provided:
class ProductFactorySpec extends Specification {
ProductRepository repository = Stub()
ProductFactory factory = new ProductFactory(repository)
def "When i decide create new product"() {
given:
repository.checkProductExists(_) >> true
when:
def result = factory.create("fakeProduct")
then:
result instanceof Product
}
}
You can force to complete the future using future.complete(true)
def "When i decide create new product"() {
def future = new CompletableFuture<Boolean>()
when:
repository.checkProductExists("Fake string") >> future
future.complete(true)
def result = this.factory.create(fakeOfferData())
then:
result instanceof Product
}
Tested class:
public class ClassForTest {
public String hello(){
return "hello " + getClassName();
}
public String getClassName(){
return ClassForTest.class.getName();
}
}
Spock class:
class ClassForSpockTest extends Specification{
def setupSpec(){
ClassForTest.metaClass.getClassName={"ClassForSpockTest"}
}
def "override test"(){
setup:
ClassForTest cft = new ClassForTest()
expect:
cft.getClassName() == "ClassForSpockTest"
}
def "mock test"(){
setup:
ClassForTest cft = new ClassForTest()
expect:
cft.hello() == "hello ClassForSpockTest"
}
}
override test test is passed!
Mock test is crashing, cft.hello() return "hello ClassForTest"
You can't use the metaclass to override a method call in a Java class from another method in that class. This is a limitation of spock, Java, and groovy. In this case, you have to use other mocking techniques. For example, you can use subclassing:
setup:
ClassForTest cft = new ClassForTest() {
String getClassName() {"ClassForSpockTest"}
}
I have an abstract base POGO:
abstract class AuthorizingResource {
void authorize(String credential) {
if(!credentialIsValid(credential)) {
throw new AuthorizationException(credential)
}
}
boolean credentialIsValid(String credential) {
// Do stuff to determine yea or nay
}
}
And many concrete subclasses like so:
class FizzResource extends AuthorizingResource {
List<Fizz> getAllFizzes(String credential) {
authorize(credential)
List<Fizz> fizzes
// Do stuff
fizzes
}
Fizz getFizzById(String credential, Long id) {
authorize(credential)
Fizz fizz
// Do stuff
fizz
}
void considerTheLillies(Buzz buzz) {
// Do stuff
}
void upsertFizz(String credential, Fizz fizz) {
authorize(credential)
// Do stuff
}
}
As you can see there's several things going on:
Any FizzResource methods that I want authenticated/authorized, I need to manually call authorize(...) at the top of the method
Some methods (considerTheLillies) do not need to be authed
I was wondering if I could mimic AOP by using a closure to call authorize(...) (so I don't have to keep adding it mindlessly) that can use some sort of pattern for selecting which methods to "wrap" inside the closure. In the particular case of the FizzResource, this would be any method that contains "*Fizz*" in it, but that pattern should be (ideally) any valid regex. The one thing that can't change is that any method that accepts credential arg cannot have its signature modified.
So basically, something like Spring AOP or Google Guice's method interceptors, but using native Groovy closures.
Any ideas?
You can use invokeMethod with GroovyInterceptable. Note that any fizz in the name will be matched:
abstract class AuthorizingResource implements GroovyInterceptable {
def invoked = []
def validator = [credentialIsValid : { true }]
void authorize(String credential) {
if ( !validator.credentialIsValid(credential) ) {
throw new RuntimeException(credential)
}
}
def invokeMethod(String method, args) {
if (method.toLowerCase().contains('fizz')) {
metaClass.getMetaMethod('authorize', String).invoke(this, args[0])
invoked.add( 'authorized ' + method )
}
return metaClass
.getMetaMethod(method, args*.getClass() as Class[])
.invoke(this, args)
}
}
class Fizz { String name }
class FizzResource extends AuthorizingResource {
List<Fizz> getAllFizzes(String credential) { ['all fizzes'] }
Fizz getFizzById(String credential, Long id) { new Fizz(name: 'john doe') }
def considerTheLillies() { 42 }
}
res = new FizzResource()
assert res.getAllFizzes('cred') == ['all fizzes']
assert res.considerTheLillies() == 42
assert res.getFizzById('cred', 10l).name == 'john doe'
assert res.invoked == ['authorized getAllFizzes', 'authorized getFizzById']
I couldn't stop thinking about a closure based solution. I came up with some Javascript style code, using closures and maps. It features no inheritance:
class AuthorizingResource {
void authorize(String credential) {
if(!credentialIsValid(credential)) {
throw new RuntimeException(credential)
}
}
boolean credentialIsValid(String credential) { true }
}
class Fizz {}
abstract class FizzResource {
abstract List<Fizz> getAllFizzes(String credential)
abstract int getFizzById(String credential, Long id)
abstract void considerTheLillies(buzz)
static createFizzResource(authorized) {
def auth = new AuthorizingResource()
def authorize = { auth.authorize it; authorized << it }
return [
getAllFizzes : { String credential -> ['fizz list'] },
getFizzById : { String credential, Long id -> 42 },
considerTheLillies : { buzz -> }
]
.collectEntries { entry ->
entry.key.toLowerCase().contains('fizz') ?
[(entry.key) : { Object[] args ->
authorize(args[0]); entry.value(*args)
}] :
entry
} as FizzResource
}
}
Testing:
def authorized = []
def fizz = FizzResource.createFizzResource(authorized)
assert authorized == []
assert fizz.getAllFizzes('getAllFizzes cred') == ['fizz list']
fizz.considerTheLillies null
assert authorized == ['getAllFizzes cred']
assert fizz.getFizzById('fizz by id cred', 90l) == 42
assert authorized == ['getAllFizzes cred', 'fizz by id cred']
Note the authorized list is very dumb, and only needed for assert purposes.
Suppose I have a Java inteface
public interface Bar {
public void baz(String st)
public void jaz()
}
I want to implement above interface anonymously in scala within a function body like:
def foo() = {
val bar : Bar = new Bar() {
// how to do that ?
}
}
If I had to, I'd write it as:
val bar = new Bar {
def baz(st: String): Unit = {
// method impl
}
def jaz(): Unit = {
// method impl
}
}
Though my preference is to avoid side-effecting methods as much as possible, they don't play very nicely with functional programming
val bar = new Bar {
def baz(st: String) {
// method impl
}
def jaz() {
// method impl
}
}