This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
## Drools
This module contains articles about Drools
### Relevant Articles:
- [Introduction to Drools](https://www.baeldung.com/drools)
- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel)
- [An Example of Backward Chaining in Drools](https://www.baeldung.com/drools-backward-chaining)
+66
View File
@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>drools</artifactId>
<name>drools</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-spring-4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring-4</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${http-component-version}</version>
</dependency>
<!-- ... -->
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-ci</artifactId>
<version>${drools-version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-decisiontables</artifactId>
<version>${drools-version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>${drools-version}</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>${drools-version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${apache-poi-version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${apache-poi-version}</version>
</dependency>
<dependency>
<groupId>org.optaplanner</groupId>
<artifactId>optaplanner-core</artifactId>
<version>${opta-planner-version}</version>
</dependency>
</dependencies>
<properties>
<http-component-version>4.4.6</http-component-version>
<drools-version>7.4.1.Final</drools-version>
<apache-poi-version>3.13</apache-poi-version>
<opta-planner-version>7.10.0.Final</opta-planner-version>
</properties>
</project>
@@ -0,0 +1,30 @@
package com.baeldung.drools.backward_chaining;
import org.kie.api.runtime.KieSession;
import com.baeldung.drools.config.DroolsBeanFactory;
import com.baeldung.drools.model.Fact;
import com.baeldung.drools.model.Result;
public class BackwardChaining {
public static void main(String[] args) {
Result result = new BackwardChaining().backwardChaining();
System.out.println(result.getValue());
result.getFacts()
.stream()
.forEach(System.out::println);
}
public Result backwardChaining() {
Result result = new Result();
KieSession ksession = new DroolsBeanFactory().getKieSession();
ksession.setGlobal("result", result);
ksession.insert(new Fact("Asia", "Planet Earth"));
ksession.insert(new Fact("China", "Asia"));
ksession.insert(new Fact("Great Wall of China", "China"));
ksession.fireAllRules();
return result;
}
}
@@ -0,0 +1,108 @@
package com.baeldung.drools.config;
import org.drools.decisiontable.DecisionTableProviderImpl;
import org.kie.api.KieServices;
import org.kie.api.builder.*;
import org.kie.api.io.Resource;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.builder.DecisionTableConfiguration;
import org.kie.internal.builder.DecisionTableInputType;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class DroolsBeanFactory {
private static final String RULES_PATH = "com/baeldung/drools/rules/";
private KieServices kieServices=KieServices.Factory.get();
private KieFileSystem getKieFileSystem() throws IOException{
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
List<String> rules=Arrays.asList("BackwardChaining.drl","SuggestApplicant.drl","Product_rules.xls");
for(String rule:rules){
kieFileSystem.write(ResourceFactory.newClassPathResource(rule));
}
return kieFileSystem;
}
public KieContainer getKieContainer() throws IOException {
getKieRepository();
KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem());
kb.buildAll();
KieModule kieModule = kb.getKieModule();
KieContainer kContainer = kieServices.newKieContainer(kieModule.getReleaseId());
return kContainer;
}
private void getKieRepository() {
final KieRepository kieRepository = kieServices.getRepository();
kieRepository.addKieModule(new KieModule() {
public ReleaseId getReleaseId() {
return kieRepository.getDefaultReleaseId();
}
});
}
public KieSession getKieSession(){
getKieRepository();
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/BackwardChaining.drl"));
kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/SuggestApplicant.drl"));
kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Product_rules.xls"));
KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
kb.buildAll();
KieModule kieModule = kb.getKieModule();
KieContainer kContainer = kieServices.newKieContainer(kieModule.getReleaseId());
return kContainer.newKieSession();
}
public KieSession getKieSession(Resource dt) {
KieFileSystem kieFileSystem = kieServices.newKieFileSystem()
.write(dt);
KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem)
.buildAll();
KieRepository kieRepository = kieServices.getRepository();
ReleaseId krDefaultReleaseId = kieRepository.getDefaultReleaseId();
KieContainer kieContainer = kieServices.newKieContainer(krDefaultReleaseId);
KieSession ksession = kieContainer.newKieSession();
return ksession;
}
/*
* Can be used for debugging
* Input excelFile example: com/baeldung/drools/rules/Discount.xls
*/
public String getDrlFromExcel(String excelFile) {
DecisionTableConfiguration configuration = KnowledgeBuilderFactory.newDecisionTableConfiguration();
configuration.setInputType(DecisionTableInputType.XLS);
Resource dt = ResourceFactory.newClassPathResource(excelFile, getClass());
DecisionTableProviderImpl decisionTableProvider = new DecisionTableProviderImpl();
String drl = decisionTableProvider.loadFromResource(dt, null);
return drl;
}
}
@@ -0,0 +1,48 @@
package com.baeldung.drools.model;
public class Applicant {
private String name;
private int age;
private double currentSalary;
private int experienceInYears;
public Applicant(String name, int age, Double currentSalary, int experienceInYears) {
this.name = name;
this.age = age;
this.currentSalary = currentSalary;
this.experienceInYears = experienceInYears;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Double getCurrentSalary() {
return currentSalary;
}
public void setCurrentSalary(Double currentSalary) {
this.currentSalary = currentSalary;
}
public int getExperienceInYears() {
return experienceInYears;
}
public void setExperienceInYears(int experienceInYears) {
this.experienceInYears = experienceInYears;
}
}
@@ -0,0 +1,44 @@
package com.baeldung.drools.model;
public class Customer {
private CustomerType type;
private int years;
private int discount;
public Customer(CustomerType type, int numOfYears) {
super();
this.type = type;
this.years = numOfYears;
}
public CustomerType getType() {
return type;
}
public void setType(CustomerType type) {
this.type = type;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
public int getDiscount() {
return discount;
}
public void setDiscount(int discount) {
this.discount = discount;
}
public enum CustomerType {
INDIVIDUAL, BUSINESS;
}
}
@@ -0,0 +1,69 @@
package com.baeldung.drools.model;
import org.kie.api.definition.type.Position;
public class Fact {
@Position(0)
private String element;
@Position(1)
private String place;
public Fact(String element, String place) {
this.element = element;
this.place = place;
}
public String getElement() {
return element;
}
public void setElement(String element) {
this.element = element;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((element == null) ? 0 : element.hashCode());
result = prime * result + ((place == null) ? 0 : place.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Fact other = (Fact) obj;
if (element == null) {
if (other.element != null)
return false;
} else if (!element.equals(other.element))
return false;
if (place == null) {
if (other.place != null)
return false;
} else if (!place.equals(other.place))
return false;
return true;
}
@Override
public String toString() {
return "Fact{" + "element='" + element + '\'' + ", place='" + place + '\'' + '}';
}
}
@@ -0,0 +1,38 @@
package com.baeldung.drools.model;
public class Product {
private String name;
private String type;
private String label;
public Product(String name, String type) {
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.drools.model;
import java.util.ArrayList;
import java.util.List;
public class Result {
private String value;
private List<String> facts = new ArrayList<>();
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public List<String> getFacts() {
return facts;
}
public void setFacts(List<String> facts) {
this.facts = facts;
}
public void addFact(String fact) {
this.facts.add(fact);
}
}
@@ -0,0 +1,14 @@
package com.baeldung.drools.model;
public class SuggestedRole {
private String role;
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
@@ -0,0 +1,63 @@
package com.baeldung.drools.optaplanner;
import java.util.ArrayList;
import java.util.List;
import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty;
import org.optaplanner.core.api.domain.solution.PlanningScore;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty;
import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@PlanningSolution
public class CourseSchedule {
Logger logger = LoggerFactory.getLogger("CourseSchedule");
private List<Integer> roomList;
private List<Integer> periodList;
private List<Lecture> lectureList;
private HardSoftScore score;
public CourseSchedule(){
roomList = new ArrayList<>();
periodList = new ArrayList<>();
lectureList = new ArrayList<>();
}
@ValueRangeProvider(id = "availableRooms")
@ProblemFactCollectionProperty
public List<Integer> getRoomList() {
return roomList;
}
@ValueRangeProvider(id = "availablePeriods")
@ProblemFactCollectionProperty
public List<Integer> getPeriodList() {
return periodList;
}
@PlanningEntityCollectionProperty
public List<Lecture> getLectureList() {
return lectureList;
}
@PlanningScore
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
public void printCourseSchedule() {
lectureList.stream()
.map(c -> "Lecture in Room " + c.getRoomNumber().toString() + " during Period " + c.getPeriod().toString())
.forEach(k -> logger.info(k));
}
}
@@ -0,0 +1,30 @@
package com.baeldung.drools.optaplanner;
import org.optaplanner.core.api.domain.entity.PlanningEntity;
import org.optaplanner.core.api.domain.variable.PlanningVariable;
@PlanningEntity
public class Lecture {
private Integer roomNumber;
private Integer period;
@PlanningVariable(valueRangeProviderRefs = {"availablePeriods"})
public Integer getPeriod() {
return period;
}
@PlanningVariable(valueRangeProviderRefs = {"availableRooms"})
public Integer getRoomNumber() {
return roomNumber;
}
public void setPeriod(Integer period) {
this.period = period;
}
public void setRoomNumber(Integer roomNumber) {
this.roomNumber = roomNumber;
}
}
@@ -0,0 +1,32 @@
package com.baeldung.drools.optaplanner;
import java.util.HashSet;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator;
public class ScoreCalculator implements EasyScoreCalculator<CourseSchedule> {
@Override
public Score calculateScore(CourseSchedule courseSchedule) {
int hardScore = 0;
int softScore = 0;
HashSet<String> occupiedRooms = new HashSet<>();
for (Lecture lecture : courseSchedule.getLectureList()) {
if(lecture.getPeriod() != null && lecture.getRoomNumber() != null) {
String roomInUse = lecture.getPeriod().toString() + ":" + lecture.getRoomNumber().toString();
if (occupiedRooms.contains(roomInUse)) {
hardScore += -1;
} else {
occupiedRooms.add(roomInUse);
}
} else {
hardScore += -1;
}
}
return HardSoftScore.valueOf(hardScore, softScore);
}
}
@@ -0,0 +1,23 @@
package com.baeldung.drools.service;
import com.baeldung.drools.config.DroolsBeanFactory;
import com.baeldung.drools.model.Applicant;
import com.baeldung.drools.model.SuggestedRole;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import java.io.IOException;
public class ApplicantService {
KieSession kieSession=new DroolsBeanFactory().getKieSession();
public SuggestedRole suggestARoleForApplicant(Applicant applicant,SuggestedRole suggestedRole) throws IOException {
kieSession.insert(applicant);
kieSession.setGlobal("suggestedRole",suggestedRole);
kieSession.fireAllRules();
System.out.println(suggestedRole.getRole());
return suggestedRole;
}
}
@@ -0,0 +1,20 @@
package com.baeldung.drools.service;
import com.baeldung.drools.config.DroolsBeanFactory;
import com.baeldung.drools.model.Product;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
public class ProductService {
private KieSession kieSession=new DroolsBeanFactory().getKieSession();
public Product applyLabelToProduct(Product product){
kieSession.insert(product);
kieSession.fireAllRules();
System.out.println(product.getLabel());
return product;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.drools.rules
import com.baeldung.drools.model.Fact;
global com.baeldung.drools.model.Result result;
dialect "mvel"
query belongsTo(String x, String y)
Fact(x, y;)
or
(Fact(z, y;) and belongsTo(x, z;))
end
rule "Great Wall of China BELONGS TO Planet Earth"
when
belongsTo("Great Wall of China", "Planet Earth";)
then
result.setValue("Decision one taken: Great Wall of China BELONGS TO Planet Earth");
end
rule "print all facts"
when
belongsTo(element, place;)
then
result.addFact(element + " IS ELEMENT OF " + place);
end
@@ -0,0 +1,31 @@
package com.baeldung.drools.rules;
import com.baeldung.drools.model.Applicant;
global com.baeldung.drools.model.SuggestedRole suggestedRole;
dialect "mvel"
rule "Suggest Manager Role"
when
Applicant(experienceInYears > 10)
Applicant(currentSalary > 1000000 && currentSalary <= 2500000)
then
suggestedRole.setRole("Manager");
end
rule "Suggest Senior developer Role"
when
Applicant(experienceInYears > 5 && experienceInYears <= 10)
Applicant(currentSalary > 500000 && currentSalary <= 1500000)
then
suggestedRole.setRole("Senior developer");
end
rule "Suggest Developer Role"
when
Applicant(experienceInYears > 0 && experienceInYears <= 5)
Applicant(currentSalary > 200000 && currentSalary <= 1000000)
then
suggestedRole.setRole("Developer");
end
@@ -0,0 +1,14 @@
package com.baeldung.drools.optaplanner
import com.baeldung.drools.optaplanner.Lecture;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScoreHolder;
global HardSoftScoreHolder scoreHolder;
rule "noNullRoomPeriod"
when
Lecture( roomNumber == null );
Lecture( period == null );
then
scoreHolder.addHardConstraintMatch(kcontext, -1);
end
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<solver>
<scanAnnotatedClasses/>
<scoreDirectorFactory>
<scoreDrl>courseSchedule.drl</scoreDrl>
</scoreDirectorFactory>
<termination>
<secondsSpentLimit>10</secondsSpentLimit>
</termination>
</solver>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<solver>
<scanAnnotatedClasses/>
<scoreDirectorFactory>
<easyScoreCalculatorClass>com.baeldung.drools.optaplanner.ScoreCalculator</easyScoreCalculatorClass>
</scoreDirectorFactory>
<termination>
<secondsSpentLimit>10</secondsSpentLimit>
</termination>
</solver>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,36 @@
package com.baeldung.drools.backward_chaining;
import org.junit.Before;
import org.junit.Test;
import org.kie.api.runtime.KieSession;
import com.baeldung.drools.config.DroolsBeanFactory;
import com.baeldung.drools.model.Fact;
import com.baeldung.drools.model.Result;
import static junit.framework.TestCase.assertEquals;
public class BackwardChainingIntegrationTest {
private Result result;
private KieSession ksession;
@Before
public void before() {
result = new Result();
ksession = new DroolsBeanFactory().getKieSession();
}
@Test
public void whenWallOfChinaIsGiven_ThenItBelongsToPlanetEarth() {
ksession.setGlobal("result", result);
ksession.insert(new Fact("Asia", "Planet Earth"));
ksession.insert(new Fact("China", "Asia"));
ksession.insert(new Fact("Great Wall of China", "China"));
ksession.fireAllRules();
// Assert Decision one
assertEquals(result.getValue(), "Decision one taken: Great Wall of China BELONGS TO Planet Earth");
}
}
@@ -0,0 +1,49 @@
package com.baeldung.drools.optaplanner;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.api.solver.SolverFactory;
public class OptaPlannerUnitTest {
static CourseSchedule unsolvedCourseSchedule;
@BeforeAll
public static void setUp() {
unsolvedCourseSchedule = new CourseSchedule();
for(int i = 0; i < 10; i++){
unsolvedCourseSchedule.getLectureList().add(new Lecture());
}
unsolvedCourseSchedule.getPeriodList().addAll(Arrays.asList(new Integer[] { 1, 2, 3 }));
unsolvedCourseSchedule.getRoomList().addAll(Arrays.asList(new Integer[] { 1, 2 }));
}
@Test
public void test_whenCustomJavaSolver() {
SolverFactory<CourseSchedule> solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfiguration.xml");
Solver<CourseSchedule> solver = solverFactory.buildSolver();
CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule);
Assert.assertNotNull(solvedCourseSchedule.getScore());
Assert.assertEquals(-4, solvedCourseSchedule.getScore().getHardScore());
}
@Test
public void test_whenDroolsSolver() {
SolverFactory<CourseSchedule> solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfigDrools.xml");
Solver<CourseSchedule> solver = solverFactory.buildSolver();
CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule);
Assert.assertNotNull(solvedCourseSchedule.getScore());
Assert.assertEquals(0, solvedCourseSchedule.getScore().getHardScore());
}
}
@@ -0,0 +1,55 @@
package com.baeldung.drools.service;
import com.baeldung.drools.model.Applicant;
import com.baeldung.drools.model.SuggestedRole;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static junit.framework.Assert.assertNull;
import static junit.framework.TestCase.assertEquals;
public class ApplicantServiceIntegrationTest {
private ApplicantService applicantService;
@Before
public void setup() {
applicantService = new ApplicantService();
}
@Test
public void whenCriteriaMatching_ThenSuggestManagerRole() throws IOException {
Applicant applicant = new Applicant("Davis", 37, 1600000.0, 11);
SuggestedRole suggestedRole = new SuggestedRole();
applicantService.suggestARoleForApplicant(applicant, suggestedRole);
assertEquals("Manager", suggestedRole.getRole());
}
@Test
public void whenCriteriaMatching_ThenSuggestSeniorDeveloperRole() throws IOException {
Applicant applicant = new Applicant("John", 37, 1200000.0, 8);
SuggestedRole suggestedRole = new SuggestedRole();
applicantService.suggestARoleForApplicant(applicant, suggestedRole);
assertEquals("Senior developer", suggestedRole.getRole());
}
@Test
public void whenCriteriaMatching_ThenSuggestDeveloperRole() throws IOException {
Applicant applicant = new Applicant("Davis", 37, 800000.0, 3);
SuggestedRole suggestedRole = new SuggestedRole();
applicantService.suggestARoleForApplicant(applicant, suggestedRole);
assertEquals("Developer", suggestedRole.getRole());
}
@Test
public void whenCriteriaNotMatching_ThenNoRole() throws IOException {
Applicant applicant = new Applicant("John", 37, 1200000.0, 5);
SuggestedRole suggestedRole = new SuggestedRole();
applicantService.suggestARoleForApplicant(applicant, suggestedRole);
assertNull(suggestedRole.getRole());
}
}
@@ -0,0 +1,56 @@
package com.baeldung.drools.service;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.kie.api.io.Resource;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import com.baeldung.drools.config.DroolsBeanFactory;
import com.baeldung.drools.model.Customer;
import com.baeldung.drools.model.Customer.CustomerType;
public class DiscountExcelIntegrationTest {
private KieSession kSession;
@Before
public void setup() {
Resource resource = ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Discount.xls", getClass());
kSession = new DroolsBeanFactory().getKieSession(resource);
}
@Test
public void giveIndvidualLongStanding_whenFireRule_thenCorrectDiscount() throws Exception {
Customer customer = new Customer(CustomerType.INDIVIDUAL, 5);
kSession.insert(customer);
kSession.fireAllRules();
assertEquals(customer.getDiscount(), 15);
}
@Test
public void giveIndvidualRecent_whenFireRule_thenCorrectDiscount() throws Exception {
Customer customer = new Customer(CustomerType.INDIVIDUAL, 1);
kSession.insert(customer);
kSession.fireAllRules();
assertEquals(customer.getDiscount(), 5);
}
@Test
public void giveBusinessAny_whenFireRule_thenCorrectDiscount() throws Exception {
Customer customer = new Customer(CustomerType.BUSINESS, 0);
kSession.insert(customer);
kSession.fireAllRules();
assertEquals(customer.getDiscount(), 20);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.drools.service;
import com.baeldung.drools.model.Product;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class ProductServiceIntegrationTest {
private ProductService productService;
@Before
public void setup() {
productService = new ProductService();
}
@Test
public void whenProductTypeElectronic_ThenLabelBarcode() {
Product product = new Product("Microwave", "Electronic");
product = productService.applyLabelToProduct(product);
assertEquals("BarCode", product.getLabel());
}
@Test
public void whenProductTypeBook_ThenLabelIsbn() {
Product product = new Product("AutoBiography", "Book");
product = productService.applyLabelToProduct(product);
assertEquals("ISBN", product.getLabel());
}
}