3

I'm using the Stream API to determine how many items in a list meet a certain condition, but when I attempt to unit test it, it fails.

More specifically, I'm using the Stream API in a static method whose class I am statically mocking using PowerMockito, but I've configured the method in question to run normally when invoked.

As a simple example (in which I've been able to reproduce the problem), let's say I have a class called TestStream with two static methods: numPositive, which takes a List of Integers and returns how many are positive, and methodToBeMocked, which will be mocked in the test.

import java.util.List;

public class TestStream {

    public static int numPositive(List<Integer> nums) {
        return (int) nums.stream().filter(num -> num > 0).count();
    }

    public static int methodToBeMocked(int arg) {
        return arg * 2;
    }
}

And then I have the following test class:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ TestStream.class })
public class TestStreamTest {

    @Before
    public void setup() {
        PowerMockito.mockStatic(TestStream.class);
        PowerMockito.when(TestStream.numPositive(any())).thenCallRealMethod();
        PowerMockito.when(TestStream.methodToBeMocked(anyInt())).thenReturn(-1);
    }

    @Test
    public void testNumPositive() {
        List<Integer> nums = Arrays.asList(1, -1, 14, 7, -5);
        assertEquals(3, TestStream.numPositive(nums));
    }
}

When I run the test, the assertion fails saying that the actual returned value is zero. However, when I step through the code while debugging with IntelliJ and get to the numPositive method, if I evaluate the expression using the debugger, I get 3, which is what I expect.

Why would I get different results when evaluating an expression while debugging vs. running the test? Could PowerMockito be interfering with the filter method somehow?

bhawk90
  • 321
  • 1
  • 2
  • 7

0 Answers0