Which dependencies are required to import `io.mockk.every` when writing Kotlin tests with Mockk? - mockk

I'm trying to write a test based on just testCompile group: 'io.mockk', name: 'mockk', version: '1.7.15' but in the code below:
import io.mockk.every
import io.mockk.any
import io.mockk.Runs
import io.mockk.impl.annotations.MockK
import io.mockk.junit5.MockKExtension
#ExtendWith(MockKExtension::class)
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class ConfigDistributorTest {
#MockK
lateinit var configService: ...
#MockK
lateinit var centralisedConfigRegisterService: ...
val configDistributor = ConfigDistributor(centralisedConfigRegisterService, configService)
#Test
fun shouldDistributeConfigToComponents(){
every {
configService.readConfig(any())
} just Runs
}
}
although Runs, MockK and MockKExtension are successfully imported,
the every and any() are not available. Is io.mockk.any the correct import statement and which other dependency is required to use them?

First you need to import every. import io.mockk.every is the correct way to do it. Inside of every any is automatically imported, so you don't need to do that. Other things looks fine
Please invalidates caches, re-import project. Probably you have some issues with IDE.

Related

Kotlin top level function not visible when used from other Maven project

The following code works from within the same project:
import org.slf4j.Logger
import org.slf4j.LoggerFactory
val Any.log: Logger
get() = LoggerFactory.getLogger(this.javaClass)
Example usage:
log.info("hi!")
When I try it from another project I get a compilation error:
Cannot access 'log': it is internal in 'com.mycompany'
Why is this happening and how can I make it work?
I don't get it entirely but I've figured it out. It does work like this:
class Logger {
companion object {
val log: Logger
get() = LoggerFactory.getLogger(this.javaClass)
}
}

How to use flutter_test_config.dart

I'm trying to figure out how to use a flutter_test_config.dart file to configure a group of tests. Here is the code that I have in the file.
import 'dart:async';
import 'package:sqflite/sqflite.dart';
import 'package:mockito/mockito.dart';
class MockDatabase extends Mock implements Database {}
Future<void> main(FutureOr<void> testMain()) {
final Database db = MockDatabase();
testMain();
}
I would like to provide the db to the tests in this directory. What is the correct way to do this?

Test service from with dependencies in spock

I am working with a kotlin and spring project, Now I am trying to do the test of some service, which has some dependencies, I am having some problems, in order to get a success test. Maybe I my design is not good enough, moreover I have problems trying to call the method from the spy object, I am getting the issue: Cannot invoke real method 'getClubhouseFor' on interface based mock object. This is my code, Could you give me any idea about what I am doing bad.
Thanks in advance!!!!
This is my code:
import com.espn.csemobile.espnapp.models.UID
import com.espn.csemobile.espnapp.models.clubhouse.*
import com.espn.csemobile.espnapp.services.clubhouse.AutomatedClubhouseService
import com.espn.csemobile.espnapp.services.clubhouse.ClubhouseService
import com.espn.csemobile.espnapp.services.clubhouse.StaticClubhouseService
import com.espn.csemobile.espnapp.services.clubhouse.contexts.ClubhouseContext
import com.espn.csemobile.espnapp.services.core.CoreService
import rx.Single
import spock.lang.Specification
class ClubhouseServiceImplTest extends Specification {
StaticClubhouseService staticClubhouseService = GroovyStub()
AutomatedClubhouseService automatedClubhouseService = GroovyStub()
CoreService coreService = GroovyStub()
ClubhouseContext clubhouseContext = GroovyMock()
Clubhouse clubHouse
ClubhouseLogo clubhouseLogo
ClubhouseService spy = GroovySpy(ClubhouseService)
void setup() {
clubhouseLogo = new ClubhouseLogo("http://www.google.com", true)
clubHouse = new Clubhouse(new UID(), "summaryType", ClubhouseType.League, new ClubhouseLayout(), "summaryName", "MLB", clubhouseLogo, "http://www.google.com", "liveSportProp",new ArrayList<Integer>(), new ArrayList<ClubhouseSection>(),new ArrayList<ClubhouseAction>(), new HashMap<String, String>())
}
def "GetClubhouseFor"() {
given:
staticClubhouseService.getClubhouseFor(clubhouseContext) >> buildClubHouseMockService()
// The idea here is to get different responses it depends on the class of call.
automatedClubhouseService.getClubhouseFor(clubhouseContext ) >> buildClubHouseMockService()
spy.getClubhouseFor(clubhouseContext) >> spy.getClubhouseFor(clubhouseContext)
when:
def actual = spy.getClubhouseFor(clubhouseContext)
then:
actual != null
}
def buildClubHouseMockService(){
return Single.just(clubHouse)
}
}
The next are the classes involved in the test:
import com.espn.csemobile.espnapp.models.clubhouse.*
import com.espn.csemobile.espnapp.services.clubhouse.contexts.ClubhouseContext
import com.espn.csemobile.espnapp.services.core.CoreService
import org.springframework.context.annotation.Primary
import org.springframework.context.annotation.ScopedProxyMode
import org.springframework.stereotype.Service
import org.springframework.web.context.annotation.RequestScope
import rx.Single
interface ClubhouseService {
fun getClubhouseFor(context: ClubhouseContext): Single<Clubhouse?>
}
#Service
#RequestScope(proxyMode = ScopedProxyMode.NO)
#Primary
class ClubhouseServiceImpl(private val clubhouseContext: ClubhouseContext,
private var staticClubhouseService: StaticClubhouseService,
private var automatedClubhouseService: AutomatedClubhouseService,
private val coreService: CoreService?): ClubhouseService {
override fun getClubhouseFor(context: ClubhouseContext): Single<Clubhouse?> {
return staticClubhouseService.getClubhouseFor(clubhouseContext).flatMap { clubhouse ->
if (clubhouse != null) return#flatMap Single.just(clubhouse)
return#flatMap automatedClubhouseService.getClubhouseFor(clubhouseContext)
}
}
}
Well, first of all GroovySpy or GroovyStub do not make sense for Java or Kotlin classes because the special features of Groovy mocks are only available for Groovy classes. So don't expect to be able to mock constructors or static methods that way, if that was the reason for the usage. This is also documented here:
When Should Groovy Mocks be Favored over Regular Mocks? Groovy mocks should be used when the code under specification is written in Groovy and some of the unique Groovy mock features are needed. When called from Java code, Groovy mocks will behave like regular mocks. Note that it isn’t necessary to use a Groovy mock merely because the code under specification and/or mocked type is written in Groovy. Unless you have a concrete reason to use a Groovy mock, prefer a regular mock.
As for your problem with the spy, you cannot use a spy on an interface type. This is documented here:
A spy is always based on a real object. Hence you must provide a class type rather than an interface type, along with any constructor arguments for the type.
So either you just switch to Mock or Stub, both of which work on interface types, or you spy on the implementation class instead. In any case, my main suggestion is to read the documentation first and then try to use a new tool like Spock. My impression is that you have not used Spock before, but of course I could be wrong.

Spock Stepwise - Keep running testsuite after single failure

When using the Spock #Stepwise annotation, is there any way to configure it to not fail the entire testsuite after a single test fails?
Decided to just create a new extension called #StepThrough. All I needed to do was subclass StepwiseExtension and take out the line of code that was failing the entire test suite. Pasted code below...
StepThrough.groovy
package com.test.SpockExtensions
import org.spockframework.runtime.extension.ExtensionAnnotation
import java.lang.annotation.ElementType
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Target
/**
* Created by jchertkov on 6/22/15.
*/
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
#ExtensionAnnotation(StepThroughExtension.class)
public #interface StepThrough {}
StepThroughExtension.groovy
package com.test.SpockExtensions
import org.spockframework.runtime.extension.builtin.StepwiseExtension
import org.spockframework.runtime.model.SpecInfo
import java.lang.annotation.Annotation
/**
* Created by jchertkov on 6/22/15.
*/
public class StepThroughExtension extends StepwiseExtension {
public void visitSpecAnnotation(Annotation annotation, final SpecInfo spec) {
sortFeaturesInDeclarationOrder(spec);
includeFeaturesBeforeLastIncludedFeature(spec);
}
}
Notes:
I put the code into a package called com.test.SpockExtensions. You will need to do the same with whatever name you would like.
Java users - just change filetype from .groovy to .java

LinkageError: Loader constraint violation when running junit test with hamcrest in pde enviornment

I am trying to test a class using junit and hamcrest. here is the test that I have:
#Test
public void testConvert()
{
assertNull(converter.convert(null));
assertNull(converter.convert(CommonentityFactory.eINSTANCE.createOrganization()));
OrganizationMID organizationMID = OrganizationMID.create(DOMAIN, 1234L);
String organizationName = "organizationName";
com.demographics.app.commonentity.Organization fromOrganization = CommonentityFactory.eINSTANCE
.createOrganization();
fromOrganization.setMID(organizationMID);
fromOrganization.setNameFormatted(organizationName);
com.search.organization.ui.Organization organization = converter
.convert(fromOrganization);
assertThat(organization.getOrganizationMID(), is(organizationMID));
assertThat(organization.getOrganizationName(), is(organizationName));
}
When I run the test as a pde test, I get,
java.lang.LinkageError: loader constraint violation: loader (instance of org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader) previously initiated loading for a different type with name "org/hamcrest/Matcher"
Here are my imports:
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import org.junit.Test;
And I am using org.junit v4.8.2-v370 , mockito-core v1.8.5 and org.hamcrest.osgi v1.1
I am not sure what's wrong here, but I feel that I dont have the dependencies set up right in my pom.
Can anyone help me in figuring this one out?

Resources