我需要您对PowerMock和一些REST测试的帮助。
我想测试一个REST GET all,它通过不同的包从数据库返回数据。因此,REST方法调用executionService.getData();
@Path("interface/more/path/")
public class RestConnection {
[..]
@GET
@Path("path/{ID}/")
@Produces(MediaType.APPLICATION_JSON)
public Response showDetails(@PathParam("ID") int ID) {
if (something == 0) {
LinkedList<Integer> scenarioIDs = executionService.getData();
[..]
从不同的包中调用方法进行查找。
public class ExecutionService {
[..]
public LinkedList<Integer> getData() {
return dbLookup.getDataIDs(); //which makes a lookup in MySql
}
在我的测试中,我想模拟getData(),这样我就不会执行数据库查找,而只是返回一个预先准备好的链表,它是用其余的json编码并返回的。
@PowerMockIgnore({"javax.net.ssl.*","java.sql.*","com.mysql.jdbc.*"})
@RunWith(PowerMockRunner.class)
@PrepareForTest(ExecutionService.class)
public class RestConnectionTest {
private ExecutionService executionService = new ExecutionService();
@Before
public void setUp() {
ExecutionService executionService = PowerMock.createPartialMock(ExecutionService.class,
"getData");
}
@Test
public void testGetScenarios() {
suppress(constructor(Connection.class));
String getUrl = "/interface/more/path/path/0/";
try {
//PowerMock.mockStatic(ExecutionService.class);
// PowerMock.replay(ExecutionService.class);
PowerMock.expectPrivate(executionService, "getData").andAnswer(new IAnswer<LinkedList>() {
@Override
public LinkedList answer() throws Throwable {
LinkedList ll = new LinkedList();
ll.add(1);
ll.add(2);
ll.add(3);
return (ll);
}
});
//PowerMock.verify(ExecutionService.class);
} catch (Exception e) {
e.printStackTrace();
}
get(getUrl).
then().
assertThat().
body(
matchesJsonSchemaInClasspath("json/schema.json")
);
}
现在..不知怎的,我得到了一个
IllegalStateException - no last call on a mock available
错误和
java.net.ConnectException: Connection refused
错误。此外,似乎PowerMock执行原始的getData()方法,该方法尝试连接到数据库。这也失败了。你能帮帮我吗?
谢谢!