我有下面的类在StackOverflow中有一个答案,但是它处理了Mockito的列表抛出检查异常。我喜欢调查这种情况。没有得到我想念的地方。
public SimpleClass{
private SimpleClass(){}
public void runMethod(request,String,Map,Object,Object){
try{
doesSomething()....
}
}
catch(Exception e){
String message= ""+request.getAttribute(X)+"Some message"
Logger.Log(param1+param2+message);
}
}
Run Code Online (Sandbox Code Playgroud)
我的测试方法如下所示。我尝试使用JUnit运行覆盖范围,但未覆盖Catch块,因此编写了以下测试方法。它引发以下异常。无法到达我想念的地方。
public class SimpleClassTest{
@Test
public void testCatchBlock(){
SimpleClass instanceObj =PowerMockito.mock(SimpleClass.class);
Mockito.doThrow(new Exception()).when(instanceObj).runMethod(request, anyString(), anyMap(), anyObject(), anyObject());
}
}
Run Code Online (Sandbox Code Playgroud)
抛出异常
org.mockito.exceptions.base.MockitoException:
Checked exception is invalid for this method!
Invalid: java.lang.Exception
Run Code Online (Sandbox Code Playgroud)
编辑
我可以通过提供NullPointerException来运行该方法。当我尝试使用Junit进行代码覆盖时,catch块完全显示为红色,并且catch短语显示为黄色。如何实现100%的覆盖率以及如何在catch块中测试String消息。
我正在尝试使用 Java 8 的 LongStream 处理具有 Long 类型内容的 ArrayList,如下面给定的示例所示,但出现以下错误。
import java.util.*;
import java.util.stream.*;
public class HelloWorld{
public static void main(String []args){
List<Long> data=new LinkedList();
for(Long j=0L;j<300L;j++){
data.add(j);
}
int BATCH = 10;
LongStream.range(0, (data.size()+BATCH-1)/BATCH)
.mapToLong(i -> data.subList(i*BATCH, Math.min(data.size(), (i+1)*BATCH)))
.forEach(batch -> process(batch));
}
static void process(List<Long> list){
System.out.println(list);
}
}
Run Code Online (Sandbox Code Playgroud)
但我得到以下例外。我尝试过使用mapToLong插入地图,但mapToLong未被识别
$javac HelloWorld.java
HelloWorld.java:13: error: incompatible types: possible lossy
conversion from long to int
.map(i -> data.subList(i*BATCH, Math.min(data.size(),
(i+1)*BATCH)))
^
HelloWorld.java:14: error: incompatible types: long cannot be
converted to List<Long> …
Run Code Online (Sandbox Code Playgroud) 下面的方法返回一个Map.我正在添加一个跳过DAO如何返回值映射的伪代码.
public Map<Intger,Integer> getIDsBasingonRanks(){
Map<Integer,Integer> m = new HashMap<>();
// Dao operation fetcing values from DB;
if(dao==null){
//logging some error or info
return null;// In this cases Null Pointer will be thrown. How to handle it ?
}
m.put()// put the values inside the map from DAO
return m;
}
Run Code Online (Sandbox Code Playgroud)
现在我getIDsBasingonRanks()
从另一个返回Map的类调用并从此映射中获取值
Map<Integer,Integer> m2 = getIDsBasingonRanks();
m2.getkey();//Incase the map is null we will have Null Pointer Exception
m2.getValue(); //Incase the map is null we will have Null Pointer Exception …
Run Code Online (Sandbox Code Playgroud) 我一直在使用下面的模式匹配器来允许应用程序中的移动号码只有系列+ xxxxxxxxxxxxxx(13位或更多,不是任何 - /?,并且还限制字母表)
Pattern pattern = Pattern.compile("\\d{3})(\\[-])(\\d{4})$");
Run Code Online (Sandbox Code Playgroud)
上述正则表达式未通过验证.我错过了什么.