KotlinSpring单元试验规范

vyswwuz2  于 2021-07-23  发布在  Java
关注(0)|答案(2)|浏览(300)

我需要得到的规格查询结果。为了做到这一点,我使用了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())
pu3pd22g

pu3pd22g1#

解决了这个问题

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

8wtpewkr2#

问题是编译器不能决定什么类型 any() 应该是,因此选择哪种方法。
我不知道在哪里 any() 是来自,但如果它是来自某个模拟库,您可能可以使用 any(Specification) . 否则您可以更改的签名 any() 返回 Specification 或者把它扔给 Specification .

相关问题