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。

基础控制器::

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();
    }
}

我感到困惑的问题是:: 如何处理该单元测试中的getPageableFromRequest方法。BaseController众所周知,TestNG 需要扩展AbstractTestNGSpringContextTests,PowerMock 需要扩展PowerMockTestCase。我应该如何结合这两个工具在spring项目中进行单元测试

4

1 回答 1

0

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

于 2020-01-08T07:06:34.837 回答