简体   繁体   English

模拟尝试初始化字段

[英]Mock trying to initialize fields

I have a class that I am trying to mock and call a method on it -我有一个类,我试图模拟并在其上调用一个方法-

@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)
  }
}

I am using this method in another class as -我在另一个类中使用这种方法 -

@Service
open class SizingService(private val cloudStorageService: CloudStorageService) {
 fun methodName() {
   ...
   val fileSize = cloudStorageService.getSizeOfFirstMatchedObject("bucketName", "filename", "prefix") // trying to mock this call
   ...
 }
}

My Test File:我的测试文件:

@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)
  }
}

The s3Client is initialized as a bean in my AppConfig - 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()
  }
}

But when I run the test, I get a failure saying s3Client is uninitialized.但是当我运行测试时,我得到一个失败,说 s3Client 未初始化。 Why is it even trying to initialize the s3Client in CloudStorageService when it is a mock ?为什么当它是一个 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)

How do I properly mock this method ?如何正确模拟此方法?

I made the method that I am mocking open and the mocking worked.我使我正在模拟的方法open并且模拟工作。 But I have no idea why mockito was trying to initialize if the method is not open.但我不知道为什么如果方法未打开,mockito 会尝试初始化。 The error message also did not help.错误消息也没有帮助。

Can someone explain what mockito is actually doing and how open on a method allows the mock to happen ?有人可以解释 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.

相关问题 初始化@EJB字段 - Initialize @EJB fields 在 Spring Beans 中初始化字段的正确方法是什么? - What is a right way to initialize fields in Spring Beans? Spring可以初始化“非bean”字段吗? - Can Spring initialize “non-bean” fields? 如何在实体 JPA 中初始化其他字段大小的字段 - How to initialize fields with size others fields in entity JPA 尝试使用MockRestServiceServer模拟RestTemplate,但body始终为null - Trying to mock RestTemplate with MockRestServiceServer but body is always null 尝试在Thymeleaf中使用动态字段 - Trying to use dynamic fields in Thymeleaf 在Spring Web上下文中通过Mock对象覆盖自动装配的字段 - Overwrite autowired fields by Mock object in spring web context java.lang.NoClassDefFoundError无法初始化类org.springframework.mock.web.MockServletContext - java.lang.NoClassDefFoundError Could not initialize class org.springframework.mock.web.MockServletContext 尝试模拟 rest 模板时在响应中获取 null 指针 - Getting null pointer on response when trying to mock rest template 使用 XML 的 Spring Cloud 合同。 尝试根据请求指定模拟 - Spring cloud contract with XML. Trying to specify mock depend on request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM