How to mock an instance variable using Mockito in java?

I’m a noob to unit testing and use of mockito

I have a class

public class SystemTenancyConfig {     private String systemTenancy; } 

I have used this in another class where I’m getting the value:

 @Inject SystemTenancyConfig systemTenancyConfig; String val = systemTenancyConfig.getsystemTenancy(); 

How do I mock systemTenancyConfig.getsystemTenancy() to be set to a string say "Test"? UpdatE:

    @Mock     private SystemTenancyConfig systemTenancyConfig;        when(systemTenancyConfig.getSystemTenancy()).thenReturn("test"); 

is giving me a NPE

Add Comment
1 Answer(s)

the condition when getsystemTenancy will trigger your mock

when(systemTenancy.getsystemTenancy()).thenReturn(what you want it return);     systemTenancy.getsystemTenancy() 

also @Mock over the Object you want to mock the whole Object

example

@Inject private SystemTenancyConfig systemTenancyConfig;  @Test function void testingSomething(){    when(systemTenancyConfig.getSystemTenancy()).thenReturn("test"); // condition to trigger the mock and return test    String val = systemTenancyConfig.getsystemTenancy(); } 
Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.