【问题标题】:Using mocked objects使用模拟对象
【发布时间】:2013-08-12 11:16:08
【问题描述】:

我刚刚开始使用 Mockito 在 Android 上进行单元测试 - 如何让要测试的类使用模拟类/对象而不是常规类/对象?

【问题讨论】:

    标签: android mocking mockito


    【解决方案1】:
    1. 您可以将@InjectMocks 用于编写测试的类。

      @InjectMocks private EmployManager manager;

    2. 然后您可以将@Mock 用于您要模拟的类。这将是依赖类。

      @Mock private EmployService service;

    3. 然后编写一个设置方法以使您的测试可用。

    @Before
    public void setup() throws Exception {
      manager = new EmployManager();
      service = mock(EmployService.class);
      manager.setEmployService(service);
      MockitoAnnotations.initMocks(this);
    }
    

    然后编写你的测试。

    @Test
    public void testSaveEmploy() throws Exception {
        Employ employ = new Employ("u1");
        manager.saveEmploy(employ);
    
        // Verify if saveEmploy was invoked on service with given 'Employ'
        // object.
        verify(service).saveEmploy(employ);
    
        // Verify with Argument Matcher
        verify(service).saveEmploy(Mockito.any(Employ.class));
    }
    

    【讨论】:

    【解决方案2】:

    通过注入依赖:

    public class ClassUnderTest
        private Dependency dependency;
    
        public ClassUnderTest(Dependency dependency) {
            this.dependency = dependency;
        }
    
        // ...
    }
    
    ...
    
     Dependency mockDependency = mock(Dependency.class);
     ClassUnderTest c = new ClassUnderTest(mockDependency);
    

    您还可以使用 setter 来注入依赖项,甚至可以使用 @Mock@InjectMocks 注释直接注入私有字段(阅读 the javadoc 以了解它们如何工作的详细说明)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 2018-10-27
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多