JMockit mock protected method in superclass and st

2019-06-13 05:29发布

I am still learning JMockit and need help understanding it.

I am testing a class that uses superclass methods. My test gets a null pointer when it attempts to use the superclass method due to code inside it that uses struts action context to get the session and pull an object from the session.

The method I want to bypass the struts session stuff inside the protected method.

public class MyExtendingClass extends MySuperClass{ 
  public void methodIamTesting(){///} 
}

public abstract class MySuperClass{
  //I want to mock this method
  protected Object myProtectedSuperClassMethod(){
// struts action context code that returns an object//}
}

Test code

@Test
public void testRunsAndDoesntPass() {
Mockit.setUpMock(MySuperClass.class, new MySuperClass(){       
  public Object myProtectedSuperClassMethod() {
      return object;
  }
}); 

// real class method invocation happens
assertEquals(expected, actual);

}

I keep getting NullPointers just like if I didn't have the mock Not sure what to try next. All the docs and code samples I have read say to just declare the superclass method as public in the setUpMock and it should work.

I can't mock the entire class because that is the class I am testing.

2条回答
劳资没心,怎么记你
2楼-- · 2019-06-13 05:57

I discovered that I needed to create the MockClass then reference it using setupmock correctly.

I am really falling in love with JMockit.

@MockClass(realClass = MyExtendingClass.class)
public static class MockSuperClass {
  final Object object = new Object();

  @Mock
  public Object myProtectedSuperClassMethod() {
      return object;
 }}
@Test
public void testRunsAndNowWillPass() {

Mockit.setUpMock(MySuperClass.class, new MockSuperClass(){
public Object myProtectedSuperClassMethod() {
  return object;
}});
// real class method invocation happens where i set expected and actual
assertEquals(expected, actual);
}
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-06-13 06:21

you mask the parent class implementation out totally @Mocked final MySuperClass base

abstract class MySuperClass{
    protected Object myProtectedSuperClassMethod(){
}

class MyExtendingClass extends MySuperClass{ 
    public void methodIamTesting(){///} 
}

@Test
public void testRunsAndDoesntPass(@Mocked final MySuperClass base ) {
    //you could mask out all the base class implementation like this
    new Expectations(){{
        invoke(base, "myProtectedSuperClassMethod");
    }};

    // real class method invocation happens
    // ...
    assertEquals(expected, actual);
}
查看更多
登录 后发表回答