Загрузка тестовых свойств application.yml
У меня есть файл тестовых свойств в src/test/resources/application.yml
. Но я не могу получить значения для загрузки в модульном тесте. У меня следующий класс:
@ConfigurationProperties("snmp")
open class SnmpProperties {
var port: Int = 1611
lateinit var protocol: String
lateinit var host: String
override fun toString(): String {
return "SnmpProperties(port=$port, protocol='$protocol', host='$host')"
}
}
который в производственном коде загружает значения из /src/main/resources/application.yml
.
snmp:
port: 1161
protocol: udp
host: 0.0.0.0
Класс модульного теста:
@CamelSpringBootTest
@SpringBootApplication
@EnableAutoConfiguration
open class SnmpRouteTest : CamelTestSupport() {
@Autowired
lateinit var snmpProperties: SnmpProperties
@Mock
lateinit var repository: IPduEventRepository
@InjectMocks
lateinit var snmpTrapRoute: SnmpTrapRoute
@Before
fun setup() {
initMocks(this)
}
Я попытался добавить test
профиль для каждого application.yml
файлы, чтобы увидеть, добавляет ли это @ActiveProfiles("test")
работал, но не работал.
SRC / основные / ресурсы /application.yml и SRC / тест / ресурсы /application.yml
# Test profile
spring:
profiles: test
snmp:
port: 1161
protocol: udp
host: 0.0.0.0
Я также создал класс TestConfiguration, который создает SnmpProperties
bean и автоматически подключите его к тестовому классу, используя @EnableConfigurationProperties(TestConfiguration::class)
:
@Configuration
@EnableConfigurationProperties(SnmpProperties::class)
open class TestConfiguration {
@Bean
open fun snmpProperties() = SnmpProperties()
}
Опять нет. Я получаю следующую ошибку:
Cannot instantiate @InjectMocks field named 'snmpTrapRoute' of type 'class org.meanwhile.in.hell.camel.snmp.receiver.route.SnmpRoute'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : Parameter specified as non-null is null: method org.meanwhile.in.hell.camel.snmp.receiver.route.SnmpTrapRoute.<init>, parameter snmpProperties
2 ответа
Похоже, что bean-компонент не создан (отсюда и нулевая ошибка).
Попробуйте либо:
- добавлять
@Configuration
поверх вашего класса конфигурации SnmpProperties - добавлять
@EnableConfigurationProperties(SnmpProperties.class)
поверх вашего тестового класса
Источник: https://www.baeldung.com/configuration-properties-in-spring-boot
Обязательно проверьте структуру своего проекта. Файл свойств должен находиться в пути к классам, чтобы Spring Boot мог его найти и использовать. Например, структура проекта, определенная Maven здесь: https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html
В случае Maven ваши файлы конфигурации должны быть помещены в эти каталоги:
src/main/resources/application.yml
src/test/resources/application.yml
@CamelSpringBootTest
@SpringBootTest(classes = [SnmpTrapReceiverCamelApplication::class])
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@DisableJmx(false)
@ExtendWith(MockitoExtension::class)
@EnableAutoConfiguration
class SnmpTrapRouteTest {
object TestSnmpConstants {
const val SNMP_REAL_ENDPOINT_ID = "snmp-trap-route"
const val SNMP_DIRECT_REPLACEMENT_ENDPOINT = "direct:snmp-from"
const val TRAP_REQUEST_ID = 123456789
const val TRAP_OID = "1.2.3.4.5"
const val TRAP_PAYLOAD = "snmp-trap-payload"
}
@MockBean
lateinit var repository: IPduEventRepository
@Produce
lateinit var producerTemplate: ProducerTemplate
@Autowired
lateinit var camelContext: CamelContext
@Test
@Throws(Exception::class)
fun `Should call save method on the repository when PDU TRAP event supplied`() {
// Replace our SNMP consumer route with a dummy route than can be called from a producer internally.
// Since our snmp endpoint is an asynchronous consumer (meaning it only receives data from external events)
// we need to use the "direct:" component to allow a producer to internally call what is ordinarily an external
// event-driven endpoint. Otherwise we will get a Connection Refused error, as we cannot access the external
// system/socket.
AdviceWithRouteBuilder.adviceWith(camelContext, TestSnmpConstants.SNMP_REAL_ENDPOINT_ID) { routeBuilder ->
routeBuilder.replaceFromWith(TestSnmpConstants.SNMP_DIRECT_REPLACEMENT_ENDPOINT)
}
// Create the PDU object to send to the SNMP endpoint
val trap = PDU()
trap.type = PDU.TRAP
trap.requestID = Integer32(TestSnmpConstants.TRAP_REQUEST_ID)
trap.add(VariableBinding(OID(TestSnmpConstants.TRAP_OID), OctetString(TestSnmpConstants.TRAP_PAYLOAD)))
// "direct:" endpoints only send DefaultMessage objects. These are not castable to SnmpMessage objects,
// so need to overwrite the exchange IN message to be an SnmpMessage object
val exchange = DefaultExchange(camelContext)
exchange.setIn(SnmpMessage(camelContext, trap))
// ProducerTemplates need a default endpoint specified.
// The ProducerTemplate provides us with a producer that can directly deliver messages to consumers defined
// in the camelContext, using the "direct:" component (see above)
producerTemplate.setDefaultEndpointUri(TestSnmpConstants.SNMP_DIRECT_REPLACEMENT_ENDPOINT)
producerTemplate.send(exchange)
// Verify that the repository.save() was invoked
verify(repository, atLeast(1)).save(any())
}
}