【发布时间】:2015-08-11 20:05:37
【问题描述】:
我所处的场景
public class SecondClass{
SecondClass(FirstClass fc){
...
}
public void foo(String a,String b){
....
}
}
public class FirstClass{
private SecondClass sc;
public void init(){
sc = new SecondClass(this);
}
public void bar(List<Integer> input){
.....
sc.foo(s1,s2);
}
}
我想获取进入 foo 的字符串参数 a 和 b。测试类如下所示
@PrepareForTest({ FirstClass.class, SecondClass.class })
public class SampleTest
{
private String[] texts;
@Test
public void testBar() throws Exception
{
texts = new String[2];
final FirstClass fc = mock(FirstClass.class);
final SecondClass sc = spy(new SecondClass(fc));
doAnswer(invocation -> {
texts = (String[]) invocation.getArguments();
return null;
}).when(sc).foo(anyString(), anyString());
final List<Integer> input = new ArrayList<>();
input.add(1);
fc.bar(input);
System.out.println(texts[0]+"<>"+text[1]);
}
}
最后的 sysout 打印 nullnull。为什么 texts 数组没有更新?
【问题讨论】:
-
1/
sc是SecondClass中的本地变量,因此您的代码无效(sc在bar中未定义) 2/ 在您的测试中,您有一个sc这是一个间谍但是这个sc不是bar中使用的那个(另见1/) -
你想测试什么?头等舱的功能?那为什么要嘲笑呢?
-
@RC 我根据您的第 1 点更新了代码。
-
@FlorianSchaetz 我不想测试从 bar 传递的字符串 s1 和 s2。如果我可以在不使用/调用 sc 的情况下在我的测试中实现同样的效果,那么我会走那条路,但不知道该怎么做。
-
使用真正的
FirstClass,SecondClass模拟你以某种方式“注入”(设置器、构造器、反射),这应该可以。
标签: java unit-testing junit powermock powermockito