【问题标题】:Unit tests in kotlin with specifications带有规范的 kotlin 单元测试
【发布时间】:2021-05-12 01:10:54
【问题描述】:

我需要获取带有规范的查询结果。为此,我使用了 JpaSpecificationExecutor 的 List<T> findAll(@Nullable Specification<T> spec) 方法。问题是我不能在测试中做同样的事情,因为它有几个具有相同参数的方法。 这是我的方法:

fun getFaqList(category: FaqCategory?, subcategory: FaqCategory?, searchText: String?): List<FaqEntity> {

    val spec = Specification.where(FaqSpecification.categoryEquals(category))
        ?.and(FaqSpecification.subcategoryEquals(subcategory))
        ?.and(
            stringFieldContains("title", searchText)
                ?.or(stringFieldContains("description", searchText))
        )

    return faqRepository.findAll(spec)
}

以及我正在尝试运行的测试:

@MockK
private lateinit var faqRepository: FaqRepository

@InjectMockKs
private lateinit var faqService: FaqService

companion object {
    val FAQ_CATEGORY_ENTITY = FaqCategoryEntity(
        id = AGRICULTURE
    )

    val FAQ_SUBCATEGORY_ENTITY = FaqCategoryEntity(
        id = AGRICULTURE_GENERAL
    )

    val FAQ_ENTITY = FaqEntity(
        id = FAQ_ID,
        title = "title",
        description = "description",
        category = FAQ_CATEGORY_ENTITY,
        subcategory = FAQ_SUBCATEGORY_ENTITY
    )
}

@Test
fun `getFaqList - should return faq list`() {
    val faqList = listOf(FAQ_ENTITY)

    every { faqRepository.findAll(any()) } returns faqList

    val response = faqService.getFaqList(AGRICULTURE, AGRICULTURE_GENERAL, FAQ_SEARCH_TEXT)

    assertThat(response).isEqualTo(faqList)
}

我收到错误:

Overload resolution ambiguity. All these functions match.
public abstract fun <S : FaqEntity!> findAll(example: Example<TypeVariable(S)!>): 
(Mutable)List<TypeVariable(S)!> defined in kz.btsd.backkotlin.faq.FaqRepository
public abstract fun findAll(pageable: Pageable): Page<FaqEntity!> defined in 
kz.btsd.backkotlin.faq.FaqRepository
public abstract fun findAll(sort: Sort): (Mutable)List<FaqEntity!> defined in 
kz.btsd.backkotlin.faq.FaqRepository
public abstract fun findAll(spec: Specification<FaqEntity!>?): (Mutable)List<FaqEntity!> 
defined in kz.btsd.backkotlin.faq.FaqRepository

我应该在 findAll() 参数中写什么以便 spring 理解:

faqRepository.findAll(any())

【问题讨论】:

    标签: spring unit-testing kotlin spring-data-jpa specifications


    【解决方案1】:

    解决了问题

    every { faqRepository.findAll(any<Specification<FaqEntity>>()) } returns faqList
    

    【讨论】:

      【解决方案2】:

      问题在于编译器无法确定any() 应该是什么类型,因此无法确定选择哪种方法。

      我不确定any() 来自哪里,但如果它来自某个模拟库,您可能可以使用any(Specification)。否则,您也许可以更改any() 的签名以返回Specification 或将其转换为Specification

      【讨论】:

      • 是的,我知道问题所在,但我不能告诉 spring 完全使用 Specification 方法。 any() 来自 mockk 库。我尝试使用规范而不是 any(),在这种情况下我会得到其他错误,因为这两个对象会不同。我创建的那个,以及编译器使用的那个。所以我没有找到答案错误。
      猜你喜欢
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 2020-10-26
      • 2022-12-13
      • 1970-01-01
      相关资源
      最近更新 更多