Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java @PrepareForTest、@RunWith和lambda表达式_Java_Unit Testing_Lambda_Mockito_Powermock - Fatal编程技术网

Java @PrepareForTest、@RunWith和lambda表达式

Java @PrepareForTest、@RunWith和lambda表达式,java,unit-testing,lambda,mockito,powermock,Java,Unit Testing,Lambda,Mockito,Powermock,今天,我调试了一个相当大的测试用例,其中涉及了大量的whenNew模拟 最终,这一切归结为这样一个事实:使用@PrepareForTest和@RunWith注释和PowerMock似乎不会在正在测试的类中执行lambda表达式 下面是一个显示问题的示例: public class Solution { private int[] arr; void fillArray() { IntStream.range(0, arr.length).forEach(i -&

今天,我调试了一个相当大的测试用例,其中涉及了大量的
whenNew
模拟

最终,这一切归结为这样一个事实:使用
@PrepareForTest
@RunWith
注释和
PowerMock
似乎不会在正在测试的类中执行lambda表达式

下面是一个显示问题的示例:

public class Solution {
    private int[] arr;

    void fillArray() {
        IntStream.range(0, arr.length).forEach(i -> arr[i] = i);
    }
}
和一个测试类:

@PrepareForTest(Solution.class)
@RunWith(PowerMockRunner.class)
public class SolutionTest {
    @Test
    public void test() {
        int[] arr = new int[5];
        Solution solutionMock = mock(Solution.class);
        Whitebox.setInternalState(solutionMock, "arr", arr);
        doCallRealMethod().when(solutionMock).fillArray();

        solutionMock.fillArray();

        for (int i = 0; i < 5; i++) {
            assertEquals(i, arr[i]);
        }
}
@PrepareForTest(Solution.class)
@RunWith(PowerMockRunner.class)
公共类解决方案测试{
@试验
公开无效测试(){
int[]arr=新的int[5];
Solution solutionMock=mock(Solution.class);
设置内部状态(solutionMock,“arr”,arr);
doCallRealMethod().when(solutionMock).fillArray();
solutionMock.fillArray();
对于(int i=0;i<5;i++){
资产质量(i,arr[i]);
}
}
在前面的示例中,
fillArray
方法中的lambda表达式从未被调用,测试失败。删除
SolutionTest
上的一个(或两个)注释会使测试通过,但它并不是一个真正的解决方案,因为我想在新的时候进行一些
模拟

因此,最终我的问题是:


对于上述问题,是否有任何解决方案或至少可行的解决方法或修复方法?

此测试通过PowerMock 1.6.6和Mockito 1.10.19。请确保您的版本已升级。

请注意:Whitebox是一个“内部”类;当更新到Mockito的最新版本时,您会注意到(因为那个班不在了)。但遗憾的是,您不会更新到最新、更有趣的Mockito版本,因为PowerMock无法与任何像样的Mockito最新版本配合使用。完全脱离主题:但当您想避免此类问题时:尝试摆脱PowerMock。除非您使用它来测试第三方代码,否则没有理由使用它。您需要的一切需要PowerMock for可以在没有它的情况下进行测试-当您修复损坏的设计时;-)您是否尝试使用“spy”而不是“mock”?还有一个问题:您使用哪个版本的PowerMock?Mockito?