I'm new to spring-boot, currently trying to develop a kafka producer I want to test method that use value define in properties file. but it show value is null how solve this.I have added my property files to separate resource file in test folder also 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);
}
}
2 Answers 2
finally i find way, thanks everyone helping me.
@RunWith(SpringRunner.class)
@SpringBootTest
public class KafkaProducerImplTest {
@Autowired
private KafkaProducerInterface kpi;
@Test
public void check() {
kpi.check();
}
}
1 Comment
Annotate you test class with @RunWith(SpringRunner.class) which will load application context for you and instantiate the spring beans. To add spring boot support add @SpringBootTest(Which you already have).
You'll have to remove this line
"KafkaProducerImpl kpi = new KafkaProducerImpl();"
and autowire using interface reference instead. Something like this:
@Autowired
KafkaProducerInterface kpi;
I'm assuming you have the properties used here(ex. "kafka.brokers.local") defined in your test properties file.
1 Comment
Explore related questions
See similar questions with these tags.
KafkaProducerImplinstance.KafkaProducerInterfaceinstead of theImpland your test needs@RunWith(SpringRunner.class).