如何测试接收两个列表与Properties参数的JSON生成方法
可行测试方案分析与实现
一、核心测试点拆解
先明确需覆盖的测试维度:
- JSON生成逻辑是否匹配预期结构
- REST接口调用的请求参数、方法、路径是否合规
- 异常场景处理(如JSON生成失败、接口返回错误码)
二、工具组合推荐
如果PowerMock配置复杂导致测试失败,推荐用 Mockito + MockWebServer(Square出品的REST接口模拟工具)组合,既规避PowerMock的繁琐配置,又能精准聚焦业务逻辑与接口交互。若原方法依赖静态工具类,再结合PowerMock补充测试。
三、分步测试实现
1. 独立测试JSON生成逻辑
优先将JSON生成逻辑从原方法中抽离为独立方法(若未拆分),单独验证结构正确性:
// 抽离后的JSON生成方法示例 public String generateJson(List<DataGenerateFiles> files, List<String> params, Properties props) { // 原生成逻辑 } // 测试用例 @Test void testJsonGeneration() { // 构造测试数据 List<DataGenerateFiles> testFiles = Arrays.asList(new DataGenerateFiles("file1", "type1")); List<String> testParams = Arrays.asList("param1", "param2"); Properties testProps = new Properties(); testProps.setProperty("config.key", "test-value"); // 调用方法 String resultJson = target.generateJson(testFiles, testParams, testProps); // 验证JSON结构:用JSONObject或JSONAssert校验字段 JSONObject jsonObj = new JSONObject(resultJson); assertEquals("file1", jsonObj.getJSONArray("files").getJSONObject(0).getString("name")); assertEquals("test-value", jsonObj.getString("configKey")); }
2. 用MockWebServer测试REST接口调用
模拟真实接口响应,验证请求合法性:
@ExtendWith(MockitoExtension.class) class RestCallIntegrationTest { private MockWebServer mockWebServer; private YourService targetService; @BeforeEach void setUp() throws IOException { mockWebServer = new MockWebServer(); mockWebServer.start(); // 将目标类的接口地址替换为Mock服务器地址 targetService = new YourService(mockWebServer.url("/api/").toString()); } @AfterEach void tearDown() throws IOException { mockWebServer.shutdown(); } @Test void testRestApiCallSuccess() throws Exception { // 配置Mock接口的成功响应 mockWebServer.enqueue(new MockResponse() .setResponseCode(200) .setBody("{\"status\":\"ok\"}") .addHeader("Content-Type", "application/json")); // 构造测试参数 List<DataGenerateFiles> testFiles = Arrays.asList(new DataGenerateFiles("file1", "type1")); List<String> testParams = Arrays.asList("param1"); Properties testProps = new Properties(); // 调用待测试方法 targetService.yourTestMethod(testFiles, testParams, testProps); // 验证请求细节 RecordedRequest request = mockWebServer.takeRequest(); assertEquals("POST", request.getMethod()); assertEquals("/api/target-endpoint", request.getPath()); assertEquals("application/json", request.getHeader("Content-Type")); // 校验请求体JSON结构 String requestBody = request.getBody().readUtf8(); JSONObject requestJson = new JSONObject(requestBody); assertEquals(1, requestJson.getJSONArray("files").length()); } @Test void testRestApiCallFailure() throws Exception { // 模拟接口返回500错误 mockWebServer.enqueue(new MockResponse().setResponseCode(500)); // 验证异常处理逻辑 assertThrows(RestInvocationException.class, () -> targetService.yourTestMethod(Collections.emptyList(), Collections.emptyList(), new Properties()) ); } }
3. 依赖静态工具类时的PowerMock测试
如果原方法必须调用静态类(如静态REST客户端、静态JSON工具),用PowerMock做静态Mock:
@RunWith(PowerMockRunner.class) @PrepareForTest({StaticRestClient.class, JsonGenerator.class}) class PowerMockStaticTest { @Test void testStaticDependencyCall() { // Mock静态JSON生成方法 PowerMockito.mockStatic(JsonGenerator.class); when(JsonGenerator.buildJson(anyList(), anyList(), any(Properties.class))) .thenReturn("{\"mockData\":\"test\"}"); // Mock静态REST调用方法 PowerMockito.mockStatic(StaticRestClient.class); doNothing().when(StaticRestClient.class); StaticRestClient.sendPost(anyString(), anyString()); // 调用待测试方法 YourService target = new YourService(); target.yourTestMethod(Collections.emptyList(), Collections.emptyList(), new Properties()); // 验证静态方法调用次数与参数 PowerMockito.verifyStatic(JsonGenerator.class, times(1)); JsonGenerator.buildJson(anyList(), anyList(), any(Properties.class)); PowerMockito.verifyStatic(StaticRestClient.class, times(1)); StaticRestClient.sendPost(anyString(), eq("{\"mockData\":\"test\"}")); } }
四、关键注意事项
- 逻辑拆分:尽量将JSON生成、REST调用拆为独立方法,降低测试耦合度
- JSON校验:避免直接校验字符串相等,用JSON工具校验字段与结构,规避格式空格、换行导致的测试失败
- 异常覆盖:必须测试接口超时、返回错误码、JSON生成失败等异常场景
- 最小Mock原则:能单独测试的逻辑不Mock依赖,保证测试真实性
内容的提问来源于stack exchange,提问作者Jonathan Ortiz
相关产品推荐
相关产品推荐

