How to mock instance variable of class?

22,629

Solution 1

As in fge's comment:

All usages require @RunWith(PowerMockRunner.class) and @PrepareForTest annotated at class level.

Make sure you're using that test runner, and that you put @PrepareForTest(GenUser.class) on your test class.

(Source: https://code.google.com/p/powermock/wiki/MockitoUsage13)

Solution 2

Have a look at https://code.google.com/p/mockito/wiki/MockingObjectCreation - there are a couple of ideas there that may help you.

Share:
22,629
sawan
Author by

sawan

Working on Java Web development and Android app development

Updated on October 15, 2020

Comments

  • sawan
    sawan over 3 years

    How do i mock the variables instantiated at class level..I want to mock GenUser,UserData. how do i do it...

    I have following class

    public class Source {
    
    private  GenUser v1 = new GenUser();
    
    private  UserData v2 = new UserData();
    
    private  DataAccess v3 = new DataAccess();
    
    public String createUser(User u) {
        return v1.persistUser(u).toString();
        }
    }
    

    how do i mocked my v1 is like this

    GenUser gu=Mockito.mock(GenUser.class);
    PowerMockito.whenNew(GenUser.class).withNoArguments().thenReturn(gu);
    

    what i have written for unit test and to mock is that

    @Test
    public void testCreateUser() {
        Source scr = new Source();
        //here i have mocked persistUser method
        PowerMockito.when(v1.persistUser(Matchers.any(User.class))).thenReturn("value");
        final String s = scr.createUser(new User());
        Assert.assertEquals("value", s);
    }
    

    even if i have mocked persistUser method of GenUser v1 then also it did not return me "Value" as my return val.

    thanks in adavanced.......:D