简体   繁体   English

在测试 JUnit 中强制私有方法返回值

[英]Forcing private method return value in test JUnit

I'm trying to test a public method, which calls a private method that returns a random integer to use in the public method.我正在尝试测试一个公共方法,该方法调用一个私有方法,该方法返回一个随机整数以在公共方法中使用。

I am finding it hard to write a test since my expected outpoint always varies to my result due to the random number generator.我发现很难编写测试,因为由于随机数生成器,我的预期输出点总是与我的结果不同。 So i'm trying to make the private method return a specified value when called (in test).所以我试图让私有方法在调用时返回一个指定的值(在测试中)。

Is this possible?这可能吗?

Method:方法:

public String addLine(String arrayString){
    String[] numbers = arrayString.split(",");
    int startingSize = numbers.length;

    int newLineCounter = generateLineSpacing(startingSize);

    for (int index  =0;index <numbers.length; index++ ,newLineCounter--){
        if (newLineCounter == 0){
            numbers[index] = "\n," + numbers[index];
            newLineCounter = generateLineSpacing(startingSize);
        }
    }
    return StringUtils.arrayToCommaDelimitedString(numbers);
}


private int generateLineSpacing(int sizeOfArray) {
    Random random = new Random();

    //odd +1
    if (sizeOfArray % 2 == 1){
        sizeOfArray += 1;
    }

    //create new line in random position within range 1 - half array size
    return random.nextInt(sizeOfArray/2  -1 ) + 1;
}

Test:测试:

@Test
public void shouldAddSymbolAtNewLineLocation(){
    //given
    String expected = "2,3,\n,4";
    String startingString = "2,3,4";

    //mock out random number generator to return 2

    //when
    String result = underTest.addLine(startingString);

    //then
    assertEquals(expected, result);
}

You cannot usually mock a private method.您通常不能模拟私有方法。 By declaring the method private you are making sure no one will modify its behaviour, a test should not do that either.通过将方法声明为私有,您可以确保没有人会修改其行为,测试也不应该这样做。

What you can do here is moving the random number generator into a Supplier passed as a dependency to the class, or as a method parameter, this can be mocked then.您在这里可以做的是将随机数生成器移动到作为类的依赖项或作为方法参数传递的供应商中,然后可以对其进行模拟。

As an altenative, this answer methions that you can use PowerMock to mock private methods, I have personally not used it but I generally think it should not be done (again because you are changing a private method).作为替代方案, 这个答案认为您可以使用PowerMock来模拟私有方法,我个人没有使用过它,但我通常认为不应该这样做(再次因为您正在更改私有方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM