gpt4 book ai didi

java - 使用 `when` 应该返回不同的值

转载 作者:行者123 更新时间:2023-12-01 18:23:52 25 4
gpt4 key购买 nike

我正在编写一个单元测试,其中我正在模拟我想要测试的类中的 init 函数。

我有两个使用相同配置值的上下文变量,但是如何以两个上下文变量具有不同上下文值的方式进行模拟。到目前为止,它们都有相同的上下文。

class StandardRendererUtility @Inject constructor(app: App, private val rendererLocale: String) {

private val rendererLocaleContext: Context //has rendererLocaleContext
private val defaultLocaleContext: Context //has rendererLocaleContext

init {
val configuration = Configuration(app.getApplicationContext().getResources().getConfiguration())
configuration.setLocale(Locale(rendererLocale))
rendererLocaleContext = app.getApplicationContext().createConfigurationContext(configuration)
configuration.setLocale(Locale(DEFAULT_LOCALE))
defaultLocaleContext = app.getApplicationContext().createConfigurationContext(configuration)
}

}

我的测试功能

@RunWith(MockitoJUnitRunner::class)
class StandardRendererUtilityTest {
private lateinit var standardRendererUtility: StandardRendererUtility

@Mock
private lateinit var app: App
@Mock
private lateinit var context: Context
@Mock
private lateinit var configuration: Configuration
@Mock
private lateinit var rendererLocaleContext: Context
@Mock
private lateinit var defaultLocaleContext: Context
@Mock
private lateinit var resources: Resources
@Mock
private lateinit var rendererLocaleResources: Resources
@Mock
private lateinit var defaultLocaleResources: Resources


@Before
fun setup(){
MockitoAnnotations.initMocks(this)
`when`(app.getApplicationContext()).thenReturn(context)
`when`(context.getResources()).thenReturn(resources)
`when`(resources.getConfiguration()).thenReturn(configuration)
`when`(context.createConfigurationContext(ArgumentMatchers.any())).thenReturn(rendererLocaleContext)
//AT THIS POINT I THINK SHOULD BE CORRECTED. HOW CAN I RETURN defaultLocaleContext AS WELL
standardRendererUtility = StandardRendererUtility(app, "fr")

}

}

最佳答案

根据API您有两个选择:

  1. 链接 thenReturn() 方法调用(我更喜欢这样的可读性):

    when(context.createConfigurationContext(ArgumentMatchers.any()))
    .thenReturn(rendererLocaleContext)
    .thenReturn(defaultLocaleContext);
  2. 提供要作为 varags 返回的对象给 thenReturn()

    when(context.createConfigurationContext(ArgumentMatchers.any()))
    .thenReturn(rendererLocaleContext, defaultLocaleContext);

关于java - 使用 `when` 应该返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60262594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com