How to write Katalon Studio tests with IntelliJ IDEA and other IDEs

I want to perform JUnit test for a custom keyword which calls the RunConfiguration.getProjectDir(). Of course this method is expected to return the path of a Katalon Studio’s project directory. I made a test and ran it in Eclipse, then I got a failure because RunConfiguration.getProjectDir() returned null. I understood that RunConfiguration.getProjectDir() method requires the runtime environment of a Katalon Studio project.

Taking advice from @devalex88, I thought I should isolate my JUnit test from Katalon Studio runtime environment, wanted to find out a way to implement it. So I tried ExpandoMetaClass of Groovy language, and got a success. Let me tell you what I did.

I made a Groovy file as a JUnit test Include/scripts/groovy/my/keyword/GroovyExpandoMetaClassTest.groovy:

package my.keyword

import static org.hamcrest.CoreMatchers.*
import static org.junit.Assert.*

import org.junit.Before
import org.junit.Test

import com.kms.katalon.core.configuration.RunConfiguration

/**
 * This test demonstrates how to use so called "ExpandoMetaClass" of Groovy language.
 * See http://groovy-lang.org/metaprogramming.html#metaprogramming_emc for detail.
 * 
 * This JUnit test shows that you can dynamically override the static 
 *     getProjectDir() 
 * method of 
 *     com.kms.katalon.core.configuration.RunConfiguration
 * class. 
 * 
 * Overriding the Katalon Studio runtime engine by ExpandoMetaClass helps 
 * simplifying JUnit testcases for your custom keywords. This technique enables you 
 * to "mock" the runtime engine with just a few lines of Groovy code.
 * 
 * @author kazurayam
 *
 */
class GroovyExpandoMetaClassTest {
    private static final String PATH_X = "/Users/kazurayam/katalon-workspace/projectX"
 
    @Before
    void setup() {
        RunConfiguration.metaClass.static.getProjectDir = { -> return PATH_X }
    }

    @Test
    void testExpandoMetaClass() {
        String s = RunConfiguration.getProjectDir()
        println "[testExpandoMetaClass] " + s
        assertThat(s, is(PATH_X))
    }
}

I ran this test with Eclipse, and it passed!

With just a few line of Groovy code, I could override the static method (getProjectDir) of Katalon Studio’s core engine class (com.kms.katalon.core.configuration.RunConfiguration) runtime. This case demonstrates the power of Groovy’s metaprogramming. I feel quite comfortable with it.

Now I’ve got to know how to write JUnit tests for my custom Katalon Keywords, how to run them and see the results in Eclipse. I like this approach very much.


The source code is here:

3 Likes