簡體   English   中英

kotlin 中的單元測試與規范

[英]Unit tests in kotlin with specifications

我需要獲取帶有規范的查詢結果。 為此,我使用了 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

為了讓 spring 理解,我應該在 findAll() 參數中寫什么:

faqRepository.findAll(any())

解決了這個問題

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

問題是編譯器無法決定any()應該是什么類型,因此無法決定選擇哪種方法。

我不確定any()來自哪里,但如果它來自某些 mocking 庫,您可能可以使用any(Specification) 否則,您可能能夠更改any()的簽名以返回Specification或將其強制轉換為Specification

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM