【问题标题】:Kotlin tests with repository ( spring-boot, kotlin, jersey, jax-rs )Kotlin 使用存储库进行测试(spring-boot、kotlin、jersey、jax-rs)
【发布时间】:2019-05-20 07:20:52
【问题描述】:

我有工作的 kotlin 服务,但是当我尝试为它编写测试时,我卡住了,因为无论如何我都无法初始化我的所有服务......

@RunWith(SpringRunner::class)
class DataServiceTest {

    @InjectMocks
    private lateinit var DataService : DataService

    @Mock
    private lateinit var updateDataService: UpdateDataService

    @Test
    fun shouldUpdateCustomerEmail() {
        DataService.setNewCustomerEmail("221722", ApiEmail("test@test.org"))

    }

}

调用DataService类:

@Autowired
private lateinit var updateDataService: UpdateDataService

.....

fun setNewCustomerEmail(id: String, email: ApiEmail) {
        updateDataService.setNewCustomerEmail(id, email)
    }

调用UpdateDataService类:

@Service
open class UpdateDataService {

    @Autowired
    private lateinit var addressRepository: AddressRepository

    fun setNewCustomerEmail(id: String, email: ApiEmail) {
        val AddressList = getCustomerAddressList(id)
        mapNewEmailToAddressList(AddressList, email)
        cusAddressRepository.saveAll(AddressList)
    }

    fun getCustomerCusbaAddressList(id: String) : List<Address> {
        return addressRepository.findAddressByCustomerId( id )
    }

    fun mapNewEmailToAddressList(cusbaAddressList : List<Address>, email: ApiEmail) {
        AddressList.map { DataUtil.trimAddressFields( it ) }
        AddressList.map { it.email = email.email }
    }
}

我尝试了许多不同的 @RunWith() 属性和许多不同的 Autowire / Mock / InjectMocks 方法,但无济于事。

问题:

目前使用此代码。当测试到达 UpdateDataService.class 时,AddressRepository 将未初始化。 return addressRepository.findAddressByCustomerId( id )

问题:

我如何连接所有这些服务,以便在应用程序运行时加载服务,而且测试知道如何连接这些服务和存储库?

【问题讨论】:

  • 在UpdateDataService 我会使用构造函数注入,因为它更容易测试。此外,自动装配到私有字段使用反射,这可能会导致性能问题。
  • 谢谢,这样做了,但没有解决问题

标签: spring-boot testing kotlin jax-rs jersey-2.0


【解决方案1】:

使用 Spring Boot Test 可以轻松操作上下文

@RunWith(SpringRunner::class)
@SpringBootTest
class DataServiceTest

或提供@TestConfiguration

【讨论】:

    猜你喜欢
    • 2019-01-08
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 2020-12-04
    • 2022-01-27
    相关资源
    最近更新 更多