要在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规则。如果规则被正确触发,测试将通过。