简体   繁体   中英

EasyMock + PowerMock : How to mock field?

Let's look at this piece of code :

    public class A {

        public void doSmth() {  // pay attention - void method
           // impl
        }
    }

    public class B {
       private A a_instance; // null

       public void doSmthElse() {
          a_instance.doSmth(); // NPE here without mock
          // also do smth. else
       }
    }

Now, I have B b = new B(); and I want to test b.doSmthElse() , but I need to create a mock for a_instance object before, otherwise I will get NullPointerException ! How can I achieve this with EasyMock or PowerMock ???

@Test
public void testDoSomething()
    {
    // setup: sut
    B b = new B();
    A mockA = EasyMock.createMock(A.class);
    b.setA_instance(mockA); // If you have a setter

    // setup: expectations
    mockA.doSmth();

    // exercise
    EasyMock.replay(mockA);
    b.doSmthElse();

    // verify
    EasyMock.verify(mockA);
    }

@Test
public void testDoSomething_setUsingReflection()
    {
    // setup: sut
    B b = new B();
    A mockA = EasyMock.createMock(A.class);
    // Set the collaborator using a Spring reflection utility
    ReflectionTestUtils.setField(b, "a_instance", mockA);

    // setup: expectations
    mockA.doSmth();

    // exercise
    EasyMock.replay(mockA);
    b.doSmthElse();

    // verify
    EasyMock.verify(mockA);
    }

You can use

instanceName.methodName();
Easymock.expectLastCall(); //for void methods this is how it is done

instanceName can be mocked or actualInstance.

If u can make the method static then it is easier with powermock

Powermock.mockStatic(ClassNameContainingStaticMethod)

All static methods get mocked directly

Word of Caution:- Converting a method to static can have issues in other parts.Do it carefully

Hope it helps. All the best!

I don't see a reason why PowerMock is required here. You can achieve that with EasyMock itself.

@Test
public void testDoSmthElse() {
    A a = EasyMock.createMock(A.class);
    EasyMock.expect(a.doSmth()).andReturn(/*some value */);
    EasyMock.replay(a);

    B b = new B();
    Object whatever = b.doSmthElse();

    assert(); // psuedo-line. Add whatever assertion required
}

Note: Import appropriate classes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM