1

I want to do junit for my rule files. My rule file broadly has two things:

  1. a rule
  2. a helper function (in drools, not Java) which I am calling from then section of a rule

Now I want to test(assert) this function isolatedly based on the test case. is there any way possible to do this?

function void print(String string){
            System.out.println(string);
            return true;
 }

rule "XXYJK"
dialect "mvel"
salience 10
when
 objofTheclass : exampleClass() eval
 (
  objofTheclass.isKeyMatched("XXYJK")

 )
then
print("XXYJK");
end

Now I can call this rule from java code like this way.

statelessSession.setAgendaFilter(new RuleNameEqualsAgendaFilter("XXYJK"));

statelessSession.executeWithResults(rulesEngineParameters);

Now I want to do similar things without calling the rule itself or executing the whole drl file . Only the print() function I want to call.

cellepo
  • 4,001
  • 2
  • 38
  • 57
Witty wit
  • 11
  • 1

1 Answers1

1

If you just want to unit test your function in the rule, I'd suggest moving it to a static method in a separate class file. You can easily unit test that.

e.g. class with print as static method

package my.package
public class MyFunctions {
    public static void print(String string){
        System.out.println(string);
    }
}

You can then import the static method as a function in your rule by replacing your function definition with an import statement:

import function my.package.MyFunctions.print
pcoates
  • 2,102
  • 1
  • 9
  • 20
  • Thank you for the suggestion. But I am more interested to find out whether I can access the function from the drool file itself or not. I saw some post of accessing via Kie api but cant able to use in our project. We are using drool 5.6+ version where it is not supported. Also I was trying to generate dynamic rule so that I can append this function and test it . – Witty wit Jul 29 '19 at 08:47
  • This is a nice solution to involve even in a project with Spock/Groovy testing: I am continuing to test the `.drl` rules themselves in Spock, while I can refactor `.drl` helper functions to instead be Java static methods like here, and be able to test them in JUnit (without needing to test them via the rules [in my Spock testing]). The new Java static helpers are called from the rules, refactoring calls that used to be to `.drl` functions. – cellepo Jan 20 '21 at 20:32