0

我希望 A 类中继承的 getter 返回 MyObject 的 Mock。如果不直接在 A 中存根 getMyObject() 方法(即通过使用一些 MockBase 类),我怎么能做到这一点?

     public class Base {
         @Autowired
         private MyObject obj;
         public MyObject getMyObject(){
            return obj;
         }
     }


    public class A extends Base {
     @Autowired
     private SomeObject xyz; 

     public void myMethod(){
       MyObject  obj = getMyObject();
       //do something here
      }

    }

  public void MockBase {
      @Mock
      protected MyObject obj;

      public MyObject getMyObject(){
            return obj;
      }
  }

  public class ATest extends MockBase  {
    @InjectMocks
    private A a;

    @Mock
    private SomeObject xyz;


    @BeforeMethod
    public void setUp(){
        MockitoAnnotations.initMocks(this);
    } 

    public void MyMethod_SomeCondition_ExpectedResult{
       a.myMethod();
    }
   }
4

1 回答 1

1

那里有什么问题?它按预期工作,也许您使用的是旧版本的 Mockito。例如版本 1.9.5 :

这是您要测试的类的父类:

public class Base {
    private BaseObjectDependency base_object_dependency;

    public BaseObjectDependency getBase_object_dependency() {
        return base_object_dependency;
    }
}

这是您要测试的课程:

public class Child extends Base {
    private ChildObjectDependency child_object_dependency;

    public void myMethod() {
        BaseObjectDependency obj = getBase_object_dependency();
        //do something here
    }

    public ChildObjectDependency getChild_object_dependency() {
        return child_object_dependency;
    }
}

以下是依赖项:

public class BaseObjectDependency { }

public class ChildObjectDependency { }

现在这是 test 的父类:

import org.mockito.Mock;

public class MockBase {
    @Mock protected BaseObjectDependency base_test_dependency_mock;
}

最后是测试:

import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;

public class ChildTest extends MockBase {
    @InjectMocks private Child child;

    @Mock private ChildObjectDependency child_test_dependency_mock;


    @BeforeClass
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void check_that_mocks_are_correctly_injected() {
        assertNotNull(child.getBase_object_dependency());
        assertEquals(base_test_dependency_mock, child.getBase_object_dependency());

        assertNotNull(child.getChild_object_dependency());
        assertEquals(child_test_dependency_mock, child.getChild_object_dependency());
    }
}

你会看到我在哪里存根getBase_object_dependency()

于 2012-10-14T22:51:33.657 回答