Mocking methods of local scope objects with Mockito

后端 未结 5 1202
野性不改
野性不改 2020-11-27 02:44

I need some help with this:

Example:

void method1{
    MyObject obj1=new MyObject();
    obj1.method1();
}

I want to mock obj

5条回答
  •  轮回少年
    2020-11-27 03:21

    You could avoid changing the code (although I recommend Boris' answer) and mock the constructor, like in this example for mocking the creation of a File object inside a method. Don't forget to put the class that will create the file in the @PrepareForTest.

    package hello.easymock.constructor;
    
    import java.io.File;
    
    import org.easymock.EasyMock;
    import org.junit.Assert;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.powermock.api.easymock.PowerMock;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
        
    @RunWith(PowerMockRunner.class)
    @PrepareForTest({File.class})
    public class ConstructorExampleTest {
            
        @Test
        public void testMockFile() throws Exception {
    
            // first, create a mock for File
            final File fileMock = EasyMock.createMock(File.class);
            EasyMock.expect(fileMock.getAbsolutePath()).andReturn("/my/fake/file/path");
            EasyMock.replay(fileMock);
    
            // then return the mocked object if the constructor is invoked
            Class[] parameterTypes = new Class[] { String.class };
            PowerMock.expectNew(File.class, parameterTypes , EasyMock.isA(String.class)).andReturn(fileMock);
            PowerMock.replay(File.class); 
        
            // try constructing a real File and check if the mock kicked in
            final String mockedFilePath = new File("/real/path/for/file").getAbsolutePath();
            Assert.assertEquals("/my/fake/file/path", mockedFilePath);
        }
    }
    

提交回复
热议问题