[英]Mock trying to initialize fields
我有一個類,我試圖模擬並在其上調用一個方法-
@Component open class CloudStorageService {
@Autowired lateinit var s3Client: AmazonS3
fun getSizeOfFirstMatchedObject(bucketName: String, directory: String, prefix: String): Long {
val request = ListObjectsRequest().withBucketName(bucketName).withPrefix("$directory/$prefix")
val listObjects = s3Client.listObjects(request)
val objectSummary = listObjects.objectSummaries.first()
val size = objectSummary.size
return size / (1024 * 1024)
}
}
我在另一個類中使用這種方法 -
@Service
open class SizingService(private val cloudStorageService: CloudStorageService) {
fun methodName() {
...
val fileSize = cloudStorageService.getSizeOfFirstMatchedObject("bucketName", "filename", "prefix") // trying to mock this call
...
}
}
我的測試文件:
@ActiveProfiles("test")
@RunWith(SpringRunner::class)
@SpringBootTest(classes = [TestAppConfig::class])
class SizingServiceTest {
@Mock private lateinit var cloudStorageService: CloudStorageService
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
sizingService = SizingService(cloudStorageService)
}
@Test
fun shouldReturnDropletSizeForChainBusinessesCorrectly() {
`when`(cloudStorageService.getSizeOfFirstMatchedObject(eq("b1")!!, eq("filename"), eq(prefix))).thenReturn(200)
}
}
s3Client 在我的 AppConfig 中被初始化為 bean -
@Configuration
@EnableTransactionManagement
@EnableScheduling
open class AppConfig {
@Value("\${S3_REGION}") lateinit var awsRegion: String
@Value("\${S3_ACCESS_KEY}") lateinit var accessKey: String
@Value("\${S3_SECRET_KEY}") lateinit var secretKey: String
@Bean(name = ["s3Client"])
open fun s3Client(): AmazonS3 {
return AmazonS3ClientBuilder.standard().withRegion(awsRegion).withCredentials(AWSStaticCredentialsProvider(BasicAWSCredentials(accessKey, secretKey))).build()
}
}
但是當我運行測試時,我得到一個失敗,說 s3Client 未初始化。 為什么當它是一個 mock 時,它甚至試圖在CloudStorageService
中初始化 s3Client ?
lateinit property s3Client has not been initialized
kotlin.UninitializedPropertyAccessException: lateinit property s3Client has not been initialized
at com.service.CloudStorageService.getS3Client(CloudStorageService.kt:33)
at com.service.CloudStorageService.getSizeOfFirstMatchedObject(CloudStorageService.kt:113)
at com.service.SizingServiceTest.shouldReturnDropletSizeForChainBusinessesCorrectly(SizingServiceTest.kt:219)
如何正確模擬此方法?
我使我正在模擬的方法open
並且模擬工作。 但我不知道為什么如果方法未打開,mockito 會嘗試初始化。 錯誤消息也沒有幫助。
有人可以解釋 mockito 實際在做什么以及方法的open
性如何允許模擬發生嗎?
// Only Change I did was adding `open`.
open fun getSizeOfFirstMatchedObject(bucketName: String, directory: String, prefix: String): Long {
val request = ListObjectsRequest().withBucketName(bucketName).withPrefix("$directory/$prefix")
val listObjects = s3Client.listObjects(request)
val objectSummary = listObjects.objectSummaries.first()
val size = objectSummary.size
return size / (1024 * 1024)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.