How to mock object that implements multiple interfaces
如何模拟实现多个接口的对象
当一个 java 类实现多个接口时,模拟和设置其接口类型的期望并不困难。Mockito
提供了一些有用的方法Mockito.withSettings().extraInterfaces
来克服这个困难。让我们看看下面的例子。
Interface User
package com.wsq;
public interface User {
public String getUserName(String Id);
}
Interface Customer
package com.wsq;
public interface Customer {
public String getCustomerName(String Id);
}
Java类实现多个接口的示例
package com.wsq;
public class UserImpl implements User, Customer {
@Override
public String getCustomerName(String Id) {
return "MyCustomer";
}
@Override
public String getUserName(String Id) {
return "MyUser";
}
}
Junit Test 类来模拟和测试 UserImpl 类
package com.wsq;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public class UserTest {
private User mockWithTestData() {
User user = PowerMockito.mock(UserImpl.class ,
Mockito.withSettings().extraInterfaces(Customer.class));
PowerMockito.when(
user.getUserName(Matchers.eq("test"))).thenReturn("TestUser");
Customer customer = (Customer) user;
PowerMockito.when(
customer.getCustomerName(Matchers.eq("test"))).thenReturn("TestCustomer");
return user;
}
@Test
public void testNames() throws Exception {
// Test 1 : with test data
UserImpl userImplMock = (UserImpl) mockWithTestData();
String userName = userImplMock.getUserName("test");
String customerName = userImplMock.getCustomerName("test");
Assert.assertEquals("TestUser", userName);
Assert.assertEquals("TestCustomer", customerName);
logOutput("1 : With Mock Data", userName, customerName);
// Test 2 : with implementation data
UserImpl user = new UserImpl();
userName = user.getUserName("12345");
customerName = user.getCustomerName("12345");
Assert.assertEquals("MyUser", userName);
Assert.assertEquals("MyCustomer", customerName);
logOutput("2 : With Real Data", userName, customerName);
}
private void logOutput(String testCase, String userName, String customerName) {
System.out.println("***** Test "+testCase +" ***** :");
System.out.println("userName :" +userName);
System.out.println("customerName :" +customerName);
System.out.println("\n");
}
Console Logs
***** Test 1 : With Mock Data ***** :
userName :TestUser
customerName :TestCustomer
***** Test 2 : With Real Data ***** :
userName :MyUser
customerName :MyCustomer
最后喜欢的小伙伴,记得关注收藏哦!😏🍭😘