我在spring的单元测试中遇到问题+;testng+;莫基托+;powermock
我正在对spring项目的控制器进行单元测试,控制器代码如下:我在spring的单元测试中遇到问题+;testng+;莫基托+;powermock,spring,unit-testing,testng,powermock,Spring,Unit Testing,Testng,Powermock,我正在对spring项目的控制器进行单元测试,控制器代码如下: package app.dnatask.controller; import ... @Slf4j @RestController @RequestMapping(value = "/API/scanresultconfigure") public class ScanResultConfigureController extends BaseController { @Autowired private Sc
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);
......
}
}
}
}
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();
}
}
我使用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 ...
@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);
......
}
}
}
}
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();
}
}
包app.dnatask.controller;
导入。。。
@WebAppConfiguration
@ContextConfiguration(类={ScanResultConfigureController.class})
@组件扫描(
排除过滤器={
@ComponentScan.Filter(类型=FilterType.ANNOTATION,值={
ComponentScan.class、Configuration.class、ImportResource.class
})
},
useDefaultFilters=false,
lazyInit=true
)
@EnableWebMvc
@PrepareForTest(BaseController.class)
公共类ScanResultConfigureControllerTest扩展了AbstractTestNGSpringContextTests{
@MockBean(answer=Answers.RETURNS\u DEEP\u STUBS)
专用扫描结果配置服务扫描结果配置服务;
@自动连线
私有WebApplicationContext WebApplicationContext;
私有MockMvc-MockMvc;
@预处理法
公共作废设置(){
initMocks(this);
mockMvc=MockMvcBuilders.webAppContextSetup(webApplicationContext).dispatchOptions(true.build();
}
@试验
public void testQueryscanResultList()引发异常{
mock(BaseController.class);
当(BaseController.getPageableFromRequest),然后返回(Pageable);
Map testMap=newhashmap();
testMap.put(“键1”、“值1”);
testMap.put(“键2”、“值2”);
字符串requestJson=JSONObject.toJSONString(testMap);
List testList=new ArrayList();
添加(“test1”);
添加(“test2”);
当(scanResultConfigureService.findtitleConfigure(anyString(),anyString(),anyMap()))。然后返回(testList);
MvcResult MvcResult=mockMvc.perform(
post(“/API/scanresultconfigure/queryScanResultList/{taskId}/{externalname}”,“123”,“abc”)
.contentType(MediaType.APPLICATION_JSON)
.content(requestJson)
)
.andExpect(状态().isOk())
.andDo(print())
.andReturn();
}
}
我困惑的问题是:在单元测试中如何处理BaseController
的getPageableFromRequest
方法。众所周知,TestNG需要扩展AbstractTestNGSpringContextTests
,PowerMock需要扩展PowerMockTestCase
。在spring项目中,我应该如何结合这两种工具进行单元测试
经过多次实验,发现SpringBootTest+TestNG+PowerMock组合不起作用。解决方案是:在TestNG测试的SpringBoot项目中,使用JMockit模拟静态方法、最终方法等经过多次实验,发现SpringBootTest+TestNG+PowerMock的组合不起作用。解决方案是:在由TestNG测试的SpringBoot项目中,使用JMockit模拟静态方法、最终方法等