Showing posts with label unittesting. Show all posts
Showing posts with label unittesting. Show all posts

Wednesday, February 14, 2024

Kotlin: how to mock a static Companion method using MockK

Introduction

How do you mock a static companion method in Kotlin using MockK?

I wanted to mock this (static) method in a companion object in Kotlin in class MyClass:

  companion object {
    fun isNegativeAndFromSavingsAccount(amount: BigDecimal, accountType: accountType) = amount < BigDecimal.ZERO && accountType == AccountType.SAVINGS
  }

 Trying it with a regular 'every' like this doesn't work:

      every { MyClass.isNegativeAndFromSavingsAccount(any(), any()) } returns false

Note it does compile fine!
But when running the test, you'll get this error:

    io.mockk.MockKException: Failed matching mocking signature for left matchers: [any(), any()]
    at io.mockk.impl.recording.SignatureMatcherDetector.detect(SignatureMatcherDetector.kt:97)

Setup:

Solution

This is the way it does work:

import io.mockk.mockkObject

    mockkObject(MyClass.Companion) {
      every { MyClass.
isNegativeAndFromSavingsAccount(any(), any()) } returns false
    }

Note this did not work, got the same error:

    mockkObject(MyClass::class)
    every { MyClass.
isNegativeAndFromSavingsAccount(any(), any()) } returns false

I found several posts, but none of them gave a clear answer and/or were using some older version of MockK. E.g: https://github.com/mockk/mockk/issues/61
and this StackOverflow post.

Some more examples and variants of solutions can be found here, e.g when using @JvmStatic.

Wednesday, April 6, 2022

Configuring MySQL test-containers in your Spring Boot Java Integration Tests

Introduction

In your Integration Tests (IT) you often try to use the H2 in-memory database, to improve the speed of your integration tests. But on the other hand you want to mimic the production database as much as possible in your integration-tests.

Setting H2 in MySQL database compatibility mode tries to emulate MySQL as much as possible, but only a small subset of the differences are implemented. What for example not works correctly in H2 for JSON fields is that it escapes strings with "". For that reason you usually want to switch to for example starting a Docker database testcontainer in your IT tests, which uses a real MySQL database. With the Java-specific version in https://github.com/testcontainers/testcontainers-java.


Configuration

There are several good-to-know tips when configuring the testcontainers in your ITs.

  1. The simplest configuration is using a datasource URL in the Spring Boot properties file. This has the disadvantage that whatever database name you specify, the testcontainers library still creates a DB named 'test'. So below it will be named 'integration_test_db' you'd think, but it is still named 'test' when the IT runs:

    spring.datasource.url=jdbc:tc:mysql:5.7.32:///integration_test_db?sessionVariables=sql_mode='STRICT_TRANS_TABLES'&TC_MY_CNF=mysql&TC_INITSCRIPT=mysql/init_mysql_integration_tests.sql

    To be able to do everything on the started database, including giving it the name you want, use this URL (or see below the Java version). Notice the user 'root' in the URL:
    spring.datasource.url=jdbc:tc:mysql:5.7.32:///integration_test_db?user=root&password=&sessionVariables=sql_mode='STRICT_TRANS_TABLES'&TC_MY_CNF=mysql&TC_INITSCRIPT=mysql/init_mysql_integration_tests.sql

    Via: https://github.com/testcontainers/testcontainers-java/issues/932

  2. To initialize your database, specify the script via this extra datasource URL variable:

    TC_INITSCRIPT=mysql/init_mysql_integration_tests.sql

    Note the default directory it looks in is ..../resources for the scripts. So the full path is ..../resources/mysql/

  3. An example to prevent GROUP BY error from strict mode, add this in your TC_INITSCRIPT:

    SET GLOBAL sql_mode = 'STRICT_TRANS_TABLES';
    SET SESSION sql_mode = 'STRICT_TRANS_TABLES';


  4. To configure it in the IT Java class itself:

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = { SomeClassA.class, SomeClassB.class, ApplicationConfiguration.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    @TestPropertySource(locations = {
            "classpath:/application-test-mysql.properties" })
    @ContextConfiguration(initializers = {ThisITClass.Initializer.class})

    static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
            public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
                TestPropertyValues.of(
                        "spring.datasource.url=" + mySQLContainer.getJdbcUrl(),
                        "spring.datasource.username=" + mySQLContainer.getUsername(),
                        "spring.datasource.password=" + mySQLContainer.getPassword()
                ).applyTo(configurableApplicationContext.getEnvironment());
            }
        }

    @ClassRule
    public static MySQLContainer mySQLContainer = new MySQLContainer<>("mysql:5.7.31")
                .withUsername("root") // So now you can do a GRANT too for example
                .withPassword("") // Only possible for user 'root'
                .withEnv("MYSQL_ROOT_HOST", "%")
                .withDatabaseName("integration_test_db") // So this name will now be used, not 'test'
                .withInitScript("mysql/init_mysql_integration_tests.sql")

                ;

  5. The MySQL docker image used in the tests is retrieved from DockerHub https://hub.docker.com/_/mysql

Sunday, July 18, 2010

Best of this Week Summary 28 June - 18 July 2010

Sunday, January 31, 2010

Best of this Week Summary 25 January - 31 January 2010

Sunday, July 26, 2009

Best of this Week Summary 20 July - 26 July 2009

Thursday, November 20, 2008

JSFUnit static analysis unit testing in ADF

Introduction
Currently I'm working on the framework design of an ADF application in JDeveloper 11.1.1.0.0 (yes sometimes a man's got to do what a man's got to do ;-). One of the parts is how we are going to do (unit) testing. And one of elements in there is testing the JSF part of the ADF application. Application Developer Framework consists of several layers where the View layer consists of a JSF implementation. This JSF implementation is named ADF Faces (RichFaces) and built on top of Trinidad, the open source JSF components implementation. ADF Faces has many components Ajax-ized and has more components than Trinidad.
My eye caught JSFUnit, an open source project from JBoss. I was only able to focus on the static analysis part JSFUnit offers (it offers also other dynamic "regular unit" tests). But little information was found about that. I couldn't find any installation tips for ADF (JBoss here and here, and Websphere setup tips were available).
Thus it was just me and the computer. Here's the steps that in the end did do the job (running on Windows XP).

Setup
A couple of things are needed for all types of static analysis.

  1. Download via JSFUnit Getting Started under the section “Files”: jboss-jsfunit-core-1.0.0.Beta3.jar en jboss-jsfunit-analysis-1.0.0.Beta3.jar

  2. Note that it was not necessary to download/install myfaces-api-1.2.0.jar or JSF 1.2 API.

  3. Start JDeveloper 11.1.1.0.0 and open an ADF application with Model and ViewController project.

  4. Right-click the ViewController project, select Properties and select Libraries and Classpath in the popup. Add the above downloaded jars there.

Three types of static tests are possible with JSFUnit. I'll describe setting up each type seperately. Most information was deducted from this part of the JSFUnit documentation.

Configuration static analysis
These tests test your JSF configuration. See the above mentioned documentation part for examples of what tests are performed.
  1. Create a JUnit testclass in your ViewController project. Modify it such that it matches this example class:


    package test.com.project;

    import java.io.File;
    import java.util.HashSet;
    import java.util.Set;
    import org.jboss.jsfunit.analysis.AbstractFacesConfigTestCase;

    public class JSFUnitStaticAnalysisConfigTest extends AbstractFacesConfigTestCase {

    private static Set paths = new HashSet() {{
    // Example absolute path: add("C:/work/workspace/jsf-unit/src/faces-config.xml");
    // Relative path example below.
    add("public_html\\WEB-INF\\faces-config.xml");
    }};

    public JSFUnitStaticAnalysisConfigTest() {
    super(paths);
    }
    }



    Note the paths variable which points to the faces-config file to validate. Relative paths work too. Of course might not be valid in your test/production environment.

    Tip: notice for easier separation at deployment, I put the test class in a separate package, starting with "test.".

  2. And you're set: run the test. Of course you should see a green bar. If not, your config is probably not 100% ok (probably because what if a JSFUnit test is incorrect... Of course you then immediately contribute to the JSFUnit community project :-). I had for example several Serialization errors.

    Below is a screenshot with the result of running the config testcase:



TLD analysis
These tests test your TLDs. See the above mentioned documentation part for examples of what tests are performed.
  1. Add the dependent libraries mentioned here, at the bottom of the page: maven-taglib and commons-logging. For the commons-logging you can use the one provided by JDeveloper: Commons Logging 1.0.4. The third one, jsp-api-2.1.jar does not seem to be necessary in the ADF project.

  2. Create a JUnit testclass in the ViewController project with .tld files. Modify it such that it matches this example class:


    package test.com.project;

    import java.util.HashSet;
    import java.util.Set;
    import org.jboss.jsfunit.analysis.AbstractTldTestCase;
    import static org.junit.Assert.*;

    public class JSFUnitStaticAnalysisTLDTest extends AbstractTldTestCase {

    private static Set paths = new HashSet() {{
    // Example: add("C:/work/workspace/jsf-unit/src/demo.tld");
    add("C:\\myprojects\\app\\src\\META-INF\\myjsf.tld");
    }};

    public JSFUnitStaticAnalysisTLDTest() {
    super(paths);
    }
    }



    Note the paths variable which points to the .tld to validate. Did not try if a relative path also works.

  3. And you're set: run the test. Of course you should see a green bar. If not, your .tld is probably not 100% ok.

    Below is a screenshot with the result of running the TLD testcase:



View static analysis
These tests test your JSF views. See the above mentioned documentation part for examples of what tests are performed.
  1. No extra libs are needed, so we can immediately create a JUnit testclass in the ViewController project. Modify it such that it matches this example class:


    package test.com.project;

    import java.io.File;
    import java.util.HashSet;
    import java.util.Set;
    import org.jboss.jsfunit.analysis.AbstractFacesConfigTestCase;
    import org.jboss.jsfunit.analysis.AbstractViewTestCase;

    public class JSFUnitStaticAnalysisViewTest extends AbstractViewTestCase {


    private static Set absoluteViewPaths = new HashSet() {{
    // Example: add("C:/work/project/src/home.xhtml");
    add("C:\\myprojects\\app\\mysite\\ViewController\\public_html\\detailsPage.jspx");
    }};

    private static Set recursiveViewPaths = new HashSet() {{
    // Example: add("C:/work/project/src/views");
    add("C:\\myprojects\\app\\mysite\\ViewController\\public_html");
    }};

    public JSFUnitStaticAnalysisViewTest() {
    super(absoluteViewPaths, recursiveViewPaths,
    "public_html\\WEB-INF\\faces-config.xml");
    }

    }



    Note the paths variables. Nowhere I could find what they exactly mean. The above runs a test that passes, so I assume the paths are set correctly...

  2. And you're set: run the test. Of course you should see a green bar. If not, your view is probably not 100% ok.

    Below is a screenshot with the result of running the view testcase:


Conclusion
So that's it. Not hard at all! If you want to know a bit more high level stuff about JSFUnit, check this presentation by the project lead at the Javapolis conference (currently rebranded to Devox conference). And here's another introduction presentation.

The Shale Test Framework could be an interesting alternative for unittesting JSF. Needs some more investigation...

Sunday, December 2, 2007

Best of this Week Summary 26 November - 2 December 2007

  • Nice article on designing to facilitate unittesting, e.g. using interfaces to decouple an implementation class from its dependency.

  • Here's a couple of reasons when to use and when not to use stored procedures. Most of the time it is not such a good idea to use them, except for example when having data-intensive/abstract computations, or batch-oriented operations.

  • Interesting post on how PayPal is transacting 1500 USD per second(!) every day, and that their system is completely build in-house, running on thousands single-rack Unity servers. By using this kind of chunks (instead of a mainframe approach) they can upgrade a lot cheaper, because the servers are so cheap. This distributed, highly redundant Linux approach make the system a lot less vunerable to failures. A big benefit they have using open source is that it is a lot cheaper to have a development environment that is exactly the same as the production environment, therefore reducing the chance of inconsistent results and bugs caused by difference in environments.