我是spring-boot的新手,目前正在尝试开发kafka生产商 我想测试在属性文件中使用值定义的方法。但它显示值为null如何解决此问题。我也将我的属性文件添加到测试文件夹中的单独资源文件中 this is my folder structure
@SpringBootTest
public class KafkaProducerImplTest {
@BeforeEach
void setUp() {
}
@Test
void check() {
KafkaProducerImpl kpi = new KafkaProducerImpl();
kpi.check();
}
}
@Service
public class KafkaProducerImpl implements KafkaProducerInterface
{
@Value("${kafka.brokers.local}")
private String kafkaBrokers;
@Value("${schema-registry}")
private String schemaRegistry;
private Properties config()
{
Properties props = new Properties();
props.setProperty("bootstrap.servers",kafkaBrokers);
props.setProperty("acks", "1");
props.setProperty("reties", "10");
props.setProperty("key.serializer", StringSerializer.class.getName());
props.setProperty("value.serializer",Serializer.class.getName());
props.setProperty("schema.registry.url",schemaRegistry);
return props;
}
public <K,T>KafkaProducer<K,T> getProducer()
{
return new KafkaProducer<>(config());
}
public <T>ProducerRecord createRecord(String Topic,T msg)
{
return new ProducerRecord<>(
Topic,msg
);
}
public void sendMessage(KafkaProducer producer,ProducerRecord record)
{
producer.send(record, (recordMetadata, e) -> {
if (e == null){
System.out.println("success");
}
});
producer.flush();
}
public void closeProducer(KafkaProducer producer){
producer.close();
}
public void check(){
System.out.println(schemaRegistry);
}
}
答案 0 :(得分:0)
使用@RunWith(SpringRunner.class)注释测试类,这将为您加载应用程序上下文并实例化spring Bean。要添加Spring Boot支持,请添加@SpringBootTest(您已经拥有)。
您必须删除此行
"KafkaProducerImpl kpi = new KafkaProducerImpl();"
并使用接口参考自动接线。像这样:
@Autowired
KafkaProducerInterface kpi;
我假设您具有在测试属性文件中定义的此处使用的属性(例如“ kafka.brokers.local”)。
答案 1 :(得分:0)
最终我找到了办法,谢谢大家的帮助。
@RunWith(SpringRunner.class)
@SpringBootTest
public class KafkaProducerImplTest {
@Autowired
private KafkaProducerInterface kpi;
@Test
public void check() {
kpi.check();
}
}