这是一个MySQLDAO
类类型的T. insert
方法将数据插入MySQL数据库。
package com.so.examples;
import java.util.List;
public class MySQLDAO<T> {
public void insert(List<T> data){
System.out.println("MySQLDAO.insert()");
}
}
扩展Users
类的和MySQLDAO
类。
package com.so.examples;
import java.util.List;
public class Users extends MySQLDAO<User> {
public void insert(List<User> data){
System.out.println("Users.insert()");
data.remove(0);
data.remove(0);
super.insert(data);
}
}
User
上课:
package com.so.examples;
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
我想知道如何模拟超级MySQLDAO
类,以便将数据插入SQLite数据库。
这是一个测试类本身:
package com.so.examples;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.Arrays;
import java.util.List;
import static org.mockito.ArgumentMatchers.anyObject;
import static org.powermock.api.mockito.PowerMockito.doAnswer;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.support.membermodification.MemberMatcher.methodsDeclaredIn;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;
@RunWith(PowerMockRunner.class)
@PrepareForTest({MySQLDAO.class})
public class UsersTest {
private Users users;
@Before
public void setUp() throws Exception {
suppress(methodsDeclaredIn(MySQLDAO.class));
users = spy(new Users());
}
@Test
public void mockSuperClass() throws Exception {
doAnswer(invocation -> {
Object[] arguments = invocation.getArguments();
for (Object argument : arguments) {
System.out.println("argument = " + argument);
}
return null;
}).when((MySQLDAO<User>) users).insert(anyObject());
List<User> data = Arrays.asList(new User(1, "John"), new User(2, "Smith"),
new User(3, "Alex"));
users.insert(data);
List<User> result = Arrays.asList(new User(3, "Alex"));
Mockito.verify((MySQLDAO<User>) users).insert(result);
}
}
我试过已经压制方法了,但这不是我想要的。我还试图通过MySQLDAO
模仿insert
doAnswer(...)
方法。这也不起作用。
我想打印测试:
argument = [User{id=3, name='Alex'}]
不是
argument = [User{id=1, name='John'}, User{id=2, name='Smith'}, User{id=3, name='Alex'}]
我需要模拟超类或用模拟的替换超类。 PowerMockito可以吗?