要在Spring Boot中測試Drools規則,你需要遵循以下步驟:
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency><dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>7.59.0.Final</version>
</dependency><dependency>
<groupId>org.drools</groupId>
<artifactId>drools-decisiontables</artifactId>
<version>7.59.0.Final</version>
</dependency><dependency>
<groupId>org.kie</groupId>
<artifactId>kie-spring</artifactId>
<version>7.59.0.Final</version>
</dependency>
src/main/resources
目錄下創建一個名為rules
的文件夾。在此文件夾中,創建一個名為sampleRule.drl
的文件,并添加以下內容:package com.example.drools
rule "Sample Rule"
when
$person: Person(age < 18)
then
System.out.println("Person is under 18 years old.");
end
com.example.drools
包中創建一個名為Person
的Java類,并添加以下內容:public class Person {
private String name;
private int age;
// Getters and setters
}
com.example.drools
包中創建一個名為DroolsConfig
的Java類,并添加以下內容:import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DroolsConfig {
@Bean
public KieBase kieBase() {
KieServices kieServices = KieServices.Factory.get();
KieRepository kieRepository = kieServices.getRepository();
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newClassPathResource("rules/sampleRule.drl"));
KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
kieBuilder.buildAll();
KieContainer kieContainer = kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
return kieContainer.getKieBase();
}
@Bean
public KieSession kieSession() {
return kieBase().newKieSession();
}
}
com.example.drools
包中創建一個名為DroolsTest
的Java類,并添加以下內容:import org.junit.jupiter.api.Test;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class DroolsTest {
@Autowired
private KieSession kieSession;
@Test
void testSampleRule() {
Person person = new Person();
person.setName("John Doe");
person.setAge(16);
kieSession.insert(person);
int rulesFired = kieSession.fireAllRules();
assertEquals(1, rulesFired);
}
}
現在,你可以運行DroolsTest
類中的測試用例來測試Drools規則。如果規則被正確觸發,測試將通過。