Свойство Lateinit xmlValidator не было инициализировано в тесте kotlin - PullRequest
0 голосов
/ 04 августа 2020

Пишу тест на Kotlin. В моей программе есть компонент:

@Component
class XmlValidator (
  val props: XsdProperties,
  val logger: Logger
) {

  private val XsdSchemas: Map<Pair<String, String>, String> =
    listOfNotNull(
      loadXsd(DocumentTypes.UniversalTransfer, UniversalTransfer.Version, props.transfer),
      loadXsd(DocumentTypes.UniversalCancel, UniversalCancel.Version, props.cancel)
    )
  .groupBy({ it.first }, { it.second })
  .mapValues { it.value.first() }

  private fun loadXsd(
    forType: DocumentType,
    version: String,
    path: String
  ): Pair<Pair<String, String>, String>? {
    return runCatching {
      val xsdFile = "$xsdFolder/$path"
      val xsd = this::class.java.classLoader.getResource(xsdFile).readText()
      logger.debug("Xsd loaded [$xsdFile]")
      (forType.name to version) to xsd
    }
      .onFailure { logger.error("Xsd loading for [$forType] from [$path] failed", it) }
      .getOrNull()
  }

  private fun validateAgainstXsd(xml: String, xsd: String): Boolean {
    return runCatching {
      val factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
      factory.resourceResolver = ResourceResolver()
      factory.newSchema(StreamSource(StringReader(xsd)))
        .newValidator().validate(StreamSource(StringReader(xml)))
    }
      .onFailure { logger.error("Document validation error", it) }
      .isSuccess
  }

  fun isXmlValid(tpe: String, xml: String): Boolean {
    return runCatching {
      !props.switch || check(tpe, xml, DocumentUtil.getVersion(tpe, xml))
    }.onFailure {
        logger.error("Document validation failed: document doesn't contain version", it)
      }.isSuccess
  }

  private fun check(tpe: String, xml: String, v: String):Boolean {
    val schema = XsdSchemas[tpe to v]
    return if (schema != null) {
      validateAgainstXsd(xml, schema)
    } else {
      logger.error("Document validation failed: doesn't exist schema for type [$tpe] and version [$v]")
      false
    }
  }

  companion object {
    private val projectFolder: String = System.getProperty("user.dir") //think about clean way to do this
    val xsdFolder = "bin"
  }
}

Я хочу протестировать метод isXmlValid:

@SpringBootTest
@ActiveProfiles("test")
class XmlValidatorTest {
    @Autowired
    private lateinit var xmlValidator: XmlValidator

    @Test
    fun isXmlValidTest(){
        xmlValidator.isXmlValid("tpe", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<file xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" fileId=\"KZ_EAES_320a4a79-80a5-4756-bd68-a572027131be\" version=\"1.0\" sendingDateTime=\"2020-10-17T09:30:47Z\" xsi:noNamespaceSchemaLocation=\"xsd_.xsd\">\n" +
                "\t<document>\n" +
                ....any xml strings....
                "\t</document>\n" +
                "</file>")
    }
}

Когда я запускаю тест, я вижу ошибку:

свойство lateinit xmlValidator не инициализировано kotlin .UninitializedPropertyAccessException: свойство lateinit xmlValidator не инициализировано

Как я могу это исправить?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...