0
我是JUNITS的新手,一直试图使用Mockito和PowerMockito为我的代码编写一些测试用例,但一直面临一个问题。无法模拟方法
类代码:
public class Example implements Callable<Void> {
int startIndex;
int endIndex;
ConnectionPool connPool;
Properties properties;
public Example(int start, int end,
ConnectionPool connPool, Properties properties) {
this.startIndex = start;
this.endIndex = end;
this.connPool= connPool;
this.properties = properties;
}
@Override
public Void call() throws Exception {
long startTime = System.currentTimeMillis();
try {
List<String> listInput = new ArrayList<>();
Service service = new Service(
dbConnPool, properties, startIndex, endIndex);
service.getMethod(listInput);
.
.
.
JUNIT代码:
@RunWith(PowerMockRunner.class)
@PrepareForTest()
public class ExampleTest {
@Mock
private ConnectionPool connectionPool;
@Mock
private Properties properties;
@Mock
private Service service = new Service(
connectionPool, properties, 1, 1);
@Mock
private Connection connection;
@Mock
private Statement statement;
@Mock
private ResultSet resultSet;
@InjectMocks
private Example example = new Example(
1, 1, connectionPool, properties);
@Test
public void testCall() throws Exception {
List<String> listInput= new ArrayList<>();
listInput.add("data1");
when(service.getMethod(listInput)).thenReturn(listInput);
example.call();
}
问题:如何模拟服务类和它的方法,getMethod,打电话?
说明:Service类具有方法getMethod,它与数据库交互。所以,因为我无法嘲笑这个方法,所以代码会经过,然后我必须将getMethod中的所有对象作为连接,结果集等进行嘲讽。否则会抛出NullPointerException。
请帮我理解我做错了什么,如果可能的话,请提供你的指导,告诉我应该如何处理这种方法调用的JUNITS。
该PowerMock与EasyMock,但我使用mockito PowerMockito。 我试过了:Service mockService = PowerMockito.mock(Service.class); PowerMockito.whenNew(Service.class,connectionPool,properties,1,1) .andReturn(mockService);这是抛出错误。有什么建议么? –
@AyushKumar你能否显示你得到的错误? –
它显示了一个语法错误。 我试过了你提供的另一种解决方案,但它并没有模拟方法调用,而是依然流经。 –