java jUnit测试中的访问方法变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28246750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:16:07  来源:igfitidea点击:

Access method variable in jUnit test

javajunit

提问by user3166813

How can I use 2 variable from method below in jUnit test, but Eclipse tells me that I cannot access this variable. How can I make it accesible in any way? Or I need to define tests in other class?

我如何在 jUnit 测试中使用下面方法中的 2 个变量,但 Eclipse 告诉我我无法访问这个变量。我怎样才能让它以任何方式访问?或者我需要在其他类中定义测试?

import org.junit.Assert;
import org.junit.*;

public class Sequence {

    public void MissingNumber() {  
        int[] arr = {1, 2, 3, 5, 6, 7, 8};  
        int length = arr.length;  

        int indexes = 8;
        int values = 0;  

        for (int i = 0; i < length; i++) {  
            indexes += i+1;  
            values += arr[i];  

            int result = indexes - values;  

            System.out.println("Indexes:" + indexes);
            System.out.println("Values:" + values);
            System.out.println("Missing number is: "+ result);  
        }
    }

    @Test
    public void testCase1() {
        Assert.assertEquals("4", result); //need to use result
    }

    @Test
    public void testCase2() {
        Assert.assertEquals("10", values); //need to use values
    }
}

采纳答案by janos

The idea of unit testing is that you have a method that takes given parameters and should produce some expected output. Rewriting your program to make it work that way, for example:

单元测试的想法是你有一个方法,它接受给定的参数并应该产生一些预期的输出。重写您的程序以使其以这种方式工作,例如:

public int missingNumber(int[] arr) {
    int length = arr.length;

    int indexes = 8;
    int values = 0;

    for (int i = 0; i < length; i++) {
        indexes += i + 1;
        values += arr[i];
    }

    return indexes - values;
}

@Test
public void testResultFor_1_2_3_5_6_7_8() {
    int result = missingNumber(new int[]{1, 2, 3, 5, 6, 7, 8});
    Assert.assertEquals(4, result);
}

回答by Hille

Try to really extract (and abstract) your logic into methods. Thus the methods will end up having arguments and results, making it easy to unit test each method (with differing arguments).

尝试将您的逻辑真正提取(和抽象)到方法中。因此,这些方法最终将具有参数和结果,从而可以轻松地对每个方法进行单元测试(具有不同的参数)。