Home » Java » java – Using `when` should return different values-Exceptionshub

java – Using `when` should return different values-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am writing a unit test where I am mocking the init function from the class I want to test.

I have two context variables which use same configuration value but how can I mock in a way that both context variables have a different context value. As of now they both have same context.

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

}

My test function

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

}

}
How to&Answers:

according to the API you have two options:

  1. chain the thenReturn() method calls (which I’d prefer for readaility):

    when(context.createConfigurationContext(ArgumentMatchers.any()))
          .thenReturn(rendererLocaleContext)
          .thenReturn(defaultLocaleContext);
    
  2. provide the objects to return as varags to thenReturn()

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