项目碰到的问题笔记

Jmockit打桩之替换方法测试 import mockit.MockUp how to mock void method

@Injectable
MyService service;
new MockUp<MyService>(MyService.class){
    @Mock
    public void myMethod(param){
    return;
}
};
try{
List<List<String>> fileList = new ArrayList<>();
fileList.add(new ArrayList<>());
new MockUp<ExcelUtils>(){
@mockit.Mock
public Sheet chkFileHeader(MultipartFile file)throws Exception{
        return null;
}

@mockit.Mock
public List<List<String>> chkFileContent (Sheet sheet) throws Exception{
        return fileList;
}
};
}catch(Exception e){
}

实现层的对应方法 实现层的对应方法.jpg 测试具体代码 测试具体代码.jpg

Mockito.spy(Service).具体方法;

Spy方法可以打桩测试返回类型为void的方法. 例如FileService下

public void check(Param param)throws Exception;

进行打桩测试

Mockito.spy(FileService).check(Mockito.any());

前提是FileService下写了这个check()方法.

Jmockit另外一种打桩替换的方法:

import mockit.NonStrictExpectations
@RunWith(MockitoJUnitRunner.class)
new NonStrictExpectations(可填类名){
{
systemUtilMapper.getSysDatetime();
result = “2022060112345”;
}
};

如图: 3.jpg

4.jpg

Mockit打桩之模拟抛出异常 //针对有返回值的

Mockito.when(excelUtil.excelImport(Mockito.any(),Mockito.any())).thenThrow(new EduException());//或者EduException.class
原方法: public String excelImport(MultipartFile file, String operID) throws Exception;

调用该方法的地方: 5.jpg //针对无返回值的

Mockito.doThrow(EduException.class).when(magFileImportLogService).batchUpdate(any());
原方法: pulic void batchUpdate(List<>list) throws Exception;

调用该方法的地方: 6.jpg //针对有返回值的还有另外一种特殊情况的模拟抛出异常 Mockito.when(fistudentfeeMapper.updateByPrimaryKey(any())).thenThrow(new RuntimeException()); 原方法: int updateByPrimaryKey(Fistudentfee record); 调用该方法的地方: 7.jpg 如果按照有返回值的模拟抛出异常方法写会报: checked exception is invalid for this method, 因为原方法里面没有抛异常出来. 改成new RuntimeException()或者new MockitoException(“插入失败”)即可;注意参数一定要是any()

Reference URL: [https://www.cxyzjd.com/article/weixin_43174072/112895000
https://blog.csdn.net/E_Possible/article/details/108351909](https://www.cxyzjd.com/article/weixin_43174072/112895000
https://blog.csdn.net/E_Possible/article/details/108351909)

option content input的name属性传参到后台 JSP页面的select option下拉框实现三个参数: value属性,content属性,text属性

<c:forEach items=”${list}” var=”item”>
<option name=”accountType” value=”${item.acctType}” content=”${item.acctNo}” >${item.acctName} </option>
</c:forEach>

取content属性值如下

var option = $(“#selectId option:selected”);
option.attr(“content”);

var accountType = document.getElementsByName(“accountType”);
for(var i=0;i< accountType.length;i++){
 document.getElementById(“要赋值的元素ID”).value = accountType[i].attributes.content.value;
}

包含ajax下拉框联动 8.jpg
9.jpg 10.jpg

问题:Caused by: java.lang.IllegalArgumentException: No visible constructors in class

private NoticeGenProxy noticeGenProxy( ){};将private改成public即可

Reference URL: https://blog.csdn.net/u012976879/article/details/86592134

String s1=””;String s2=””; Mockito.when(service.impl(s1, s2)).thenReturn(mock数据); controller.export( ); 方法走到service.impl(s3, s4)时,mock数据没有; 失效的原因是未按约定的参数传值

失效原因二:

Controller: 
exportWord(HttpServletResponse reponse, String applyId, HttpSession session){
    Map<String, Object> inParam = new HashMap( );
    inParam.put(Constant.APPLY_ID, applyId);
    inParam.put(Constant.SCHOOL_ID, schoolId);//schoolId事先定义好
    Map<String, Object> resultMap;
    resultMap = service.selectApplyDetail(inParam);
}

Test:
resultMap.put(“123”,”123”);//resultMap事先已定义好

一开始我是这么写的:

Map<String,Object> inParam = new HashMap( );
inParam.put(“applyId”,”123”);
Mockito.when(service.selectApplyDetail(inParam)).thenReturn(resultMap);
controller.exportWord(response, “111”,session);

测试到绿色方法块的时候死活就不是我Test定义好的resultMap, 一直返回resultMap为空, 正确方法应该这么写:

Mockito.when(service.selectApplyDetail(anyMap( ))).thenReturn(resultMap);
(引入静态类: import static org.mockito.ArgumentMatchers.anyMap; )

PowerMockito总结

@RunWith(PowerMockRunner.class)
@PrepareForTest({MyServiceImpl.class, ContextLoader.class, XdocReportRegistry.class, Method.class})
@WebAppConfiguration
@PowerMockIgnore({"javax.management.*"})
public class MyServiceImplTest{

@InjectMocks
private MyServiceImpl service = new MyServiceImpl();(或者private MyServiceImpl service;)

@Test
public void myTest()throws Exception{
WebApplicationContext webApplicationContext = PowerMockito.mock(WebApplicationContext.class);
PowerMockito.mockStatic(ContextLoader.class);---1
PowerMockito.when(ContextLoader.getCurrentWebApplicationContext()).thenReturn(webApplicationContext)---2
;
ServletContext servletContext = PowerMockito.mock(ServletContext.class);
PowerMockito.when(webApplicationContext.getServletContext()).thenReturn(servletContext);
PowerMockito.when(servletContext.getRealPath(File.separator)).thenReturn(“123”);

mock static method

首先mockStatic方法对应的类,在PrepareForTest注解加上类.class就可以when..thenReturn
doThrow抛异常 doNothingvoid method
}
}

Map<String, Object> maps = mapper.select( );
Map<String, Object> map = JSONObject.parseObject(str, Map.class);
maps.putAll(map);

BaseController

定义非static log日志方法没办法进入static方法中 比如:

protected final Logger log = LoggerFactory.getLogger(MyServiceImpl.class);slf4j
(或者private Logger log = Logger.getLogger(MyServiceImpl.class))org.apache.log4j
method body里面有public static void myMethod(Param){
try…catch(Exception e){
log.info/error(“错误”,e);//报错,必须定义static的log日志方法
}
}

提交代码sonar门禁报newInstance( )已弃用

clazz.newInstance( )被弃用可以替换成clazz.getDeclaredConstructor( ).newInstance( )
Reference Url: https://stackoverflow.com/questions/46393863/what-to-use-instead-of-class-newinstance

java.lang.NoClassDefFoundError: Could not initialize class xxx 原因及解决方法 用的是IDEA社区版,重启IDE工具,重启项目


已有 0 条评论

    感谢参与互动!