Android 使用模拟对象

Android 使用模拟对象,android,mocking,mockito,Android,Mocking,Mockito,我刚刚用Mockito在Android上开始了单元测试-如何让正在测试的类使用模拟类/对象而不是常规类/对象?通过注入依赖项: public class ClassUnderTest private Dependency dependency; public ClassUnderTest(Dependency dependency) { this.dependency = dependency; } // ... } ... Depend

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

通过注入依赖项:

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
注释直接注入私有字段(阅读以了解它们如何工作的详细说明)

  • 您可以对编写测试的类使用@InjectMocks

    @InjectMocks
    私人雇员经理

  • 然后可以对正在模拟的类使用@Mock。这将是依赖类

    @Mock
    私人就业服务

  • 然后编写一个设置方法,使测试可用

  • 然后写下你的测试

    @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));
    }
    

    你能给我一个答案吗。谢谢
    @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));
    }