Android:在使用接口测试 class 期间提供模拟实现

Android: Providing a mocked implementation during testing of a class using an interface

我有一个接口

public interface Example{

public int sum(int a, int b);

public int diff(int a, int b);

}

现在我有了这个接口的实现:

public RealMath implements Example{

public int sum(int a, int b){
    //contact server do stuff and return value.
    return val;
}

public int diff(int a, int b){
    //contact server do stuff and return value.
    return val;
}
}

并且有工厂提供相应的实现:

public class ExampleFactory(){
public static final Example getExampleIns(String val){
return new RealMath();
}
}

现在,我有一个 class User.java,它使用这个 Example 界面来完成一些工作。 我想测试 User 其中有一个调用的方法:

Example ex = ExampleFactory.getExampleIns();
ex.sum(val1, val2); 

并根据这个值做一些处理。

我想对我的代码进行单元测试,并希望有一个 Example 接口的模拟实现,这样就不需要服务器依赖性,我只是 return 接口中方法的一些模拟值。

我的想法是在调用 ExampleFactory.getExampleIns(); 时提供我的模拟实现(当测试用例为 运行 时)。

我厌倦了 Mockito (Android),它不支持静态方法模拟。

所以我有两个问题: 1. 上面的设计有什么问题,我有一个工厂和各种实现,return 根据需求选择合适的对象?

  1. 如何通过提供 Example 接口的模拟实现来测试 User.java

谢谢。

  1. What is wrong with the above design where I have a factory and various implementations and return the suitable object based on requirements?

您在工厂中交付的实现是硬编码,因此,如果您想更改实现,则必须更改代码。您无法动态更改 impl。

2.- How do I test User.java by providing my mocked implementation for Example interface?

不使用工厂,而是使用依赖注入。您可以在构造函数中将 Example 的正确实现传递给您的 User(例如),并将其存储为实例变量,以便您以后可以使用它:

private Example exampleImpl;

public User(Example exampleImpl) {
    this.exampleImpl = exampleImpl;
}

public void methodUsingExample(Integer val1, Integer val2) {
    exampleImpl.sum(val1, val2);
}

测试时,您使用 Example 模拟构建 User 实例:

Example mockExample = mock(Example.class);
User user = new User(mockExample);
// now User is using your mock
user.methodUsingExample(1, 2);