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?
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.
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.
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.
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();
Consider some testing 'sugar' with a Junit TestRule library - droolsassert.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With