我在spring + testng + mockito + powermock的单元测试中有问题

问题描述 投票:1回答:1

我正在对spring项目的控制器进行单元测试,控制器代码如下::

package app.dnatask.controller;

import ...

@Slf4j
@RestController
@RequestMapping(value = "/API/scanresultconfigure")

public class ScanResultConfigureController extends BaseController {
    @Autowired
    private ScanResultConfigureService scanResultConfigureService;

    @RequestMapping(value = "/queryScanResultList/{taskId}/{externalname}", method = RequestMethod.POST)
    public IBaseResult queryscanResultList(final HttpServletRequest request, @PathVariable final String taskId, @PathVariable final String externalname, @RequestBody Map map) throws Exception {
        return runController(new IControllRunner() {
            public void run(IOutResult or, CheckResult cr) throws Exception {
                Pageable p = getPageableFromRequest(map, "glt_msg", null);
                List list = scanResultConfigureService.findtitleConfigure(taskId, externalname, map);
                ......
            }
        }
    }
}

我使用testng + Mockito + Powermock对控制器进行单元测试。由于控制器扩展了BaseController(代码如下),因此在执行Pageable p = getPageableFromRequest (map, "glt_msg", null);时将报告NullPointerException。

BaseController ::

package app.frame.vendor.spring.springmvc.common.usercontext;

import ...

public abstract class BaseController extends BaseController_Web {
    public BaseController() {
    }

    protected Pageable getPageableFromRequest(Map map, String gltName, Sort sort) {
        ...
        return pageable;
    }
}

测试类如下::

package app.dnatask.controller;

import ...

@WebAppConfiguration
@ContextConfiguration(classes = {ScanResultConfigureController.class})
@ComponentScan(
        excludeFilters = {
                @ComponentScan.Filter(type = FilterType.ANNOTATION, value = {
                        ComponentScan.class, Configuration.class, ImportResource.class
                })
        },
        useDefaultFilters = false,
        lazyInit = true
)
@EnableWebMvc
@PrepareForTest(BaseController.class)

public class ScanResultConfigureControllerTest extends AbstractTestNGSpringContextTests {
    @MockBean(answer = Answers.RETURNS_DEEP_STUBS)
    private ScanResultConfigureService scanResultConfigureService;

    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;

    @BeforeMethod
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).dispatchOptions(true).build();
    }

     @Test
    public void testQueryscanResultList() throws Exception {
        PowerMockito.mock(BaseController.class);
        when(BaseController.getPageableFromRequest).thenReturn(Pageable);

        Map<String, String> testMap = new HashMap<>();
        testMap.put("key1", "value1");
        testMap.put("key2", "value2");
        String requestJson = JSONObject.toJSONString(testMap);
        List testList = new ArrayList();
        testList.add("test1");
        testList.add("test2");

        when(scanResultConfigureService.findtitleConfigure(anyString(), anyString(), anyMap())).thenReturn(testList);

        MvcResult mvcResult = mockMvc.perform(
                post("/API/scanresultconfigure/queryScanResultList/{taskId}/{externalname}", "123", "abc")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(requestJson)
        )
                .andExpect(status().isOk())
                .andDo(print())
                .andReturn();
    }
}

[我很困惑的问题是::在该单元测试中如何处理getPageableFromRequestBaseController方法。众所周知,TestNG需要扩展AbstractTestNGSpringContextTests,而PowerMock需要扩展PowerMockTestCase ]。在春季项目中,应该如何结合使用这两种工具进行单元测试

spring unit-testing testng powermock
1个回答
0
投票

[经过多次实验,发现SpringBootTest + TestNG + PowerMock的组合不起作用。解决方法是:在TestNG测试的SpringBoot项目中,使用JMockit模拟静态方法,最终方法等

© www.soinside.com 2019 - 2024. All rights reserved.