Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you unit test Jboss Rules (Drools) rules?

I have written a few Drools rules for my Seam application and am wondering how I go about unit testing these. Does anybody have any sample code that can show me how to go about doing this?

like image 791
Aaron Chambers Avatar asked Jul 30 '09 12:07

Aaron Chambers


People also ask

How rules are executed in Drools?

Let's quickly summarize how Drools works. Rules are written on . drl files, facts or POJOs are inserted in the Knowledge Base, then rules are applied on each fact. If a "When" part of a rule satisfies a fact, the "Then" part will execute.

What is unit testing rules?

The following guidelines describe how to write proper unit tests: Unit tests have one assert per test. Avoid if-statements in a unit test. Unit tests only “new()” the unit under test. Unit tests do not contain hard-coded values unless they have a specific meaning.

How can you improve Drools performance of rule execution?

Literal Restrictions using the operator '==' provide for faster execution as we can index using hashing to improve performance. One can bind variables to facts and their fields and then use them in subsequent field constraints. A bound variable is called a declaration.


2 Answers

Add the following code to a unit test (JUnit, TestNG, etc):

PackageBuilder builder = new PackageBuilder();

builder.addPackageFromDrl(new InputStreamReader(getClass().getResourceAsStream( "rules.drl")));

PackageBuilderErrors errors = builder.getErrors();

Assert.assertEquals(0, errors.getErrors().length);

RuleBase ruleBase  = RuleBaseFactory.newRuleBase();
ruleBase.addPackage(pkg);

StatefullSession session = ruleBase.newStatefulSession(false);

MyFactObject myFact = new MyFactObject();

session.insert(myFact);
session.fireAllRules();
like image 140
Aaron Chambers Avatar answered Sep 28 '22 06:09

Aaron Chambers


Consider some testing 'sugar' with a Junit TestRule library - droolsassert.

like image 44
Mike Avatar answered Sep 28 '22 07:09

Mike