【问题标题】:How do I test my method in another class?如何在另一个类中测试我的方法?
【发布时间】:2017-04-20 22:58:00
【问题描述】:

我大约 5 周前才开始学习计算机科学 (Java),但我仍然无法创建方法。我被分配创建一个 NFL 统计类,然后创建一个显示计算的方法。一切都很顺利,直到我在测试类中调用我的方法。这里似乎缺少什么?

NFLPlayer CLASS(包含在方法中):

private int touchdowns;
private int interceptions;
private int passingAttempts;
private int completedPasses;
private int passingYards;
private int runningYards;
private int recievingYards;
private int tackles;
private int sacks;


// Method for Quarterback rating
public double QBRating(int touchdowns, int passingAttempts, int completedPasses,
        int passingYards, int interceptions) {

        double a = (completedPasses / passingAttempts - 0.3) * 5;
        double b = (passingYards / passingAttempts - 3) * 0.25;
        double c = (touchdowns / passingAttempts) * 25;
        double d = 2.375 - (interceptions / passingAttempts * 25);
        double ratingQB = ((a + b + c + d) / 6) * 100;
        {
        return ratingQB;
        }   

}

现在这是我的测试类,我无法显示我的计算

class MyTest {
public static void main(String[] args) {

    NFLPlayer playerStats = new NFLPlayer();

    //Player1 finding quarterback rating
    int touchdowns = 2;
    int passingAttempts = 44;
    int passingYards = 285;
    int interceptions = 1;
    int completedPasses = 35;

    // Call QB rating method
    playerStats.QBRating(touchdowns, passingAttempts, completedPasses,
            passingYards, interceptions); 

    System.out.println(QBRating);
}

}

【问题讨论】:

  • 你的 QBRating 方法返回 double 只是收集结果为 double 然后用 sysout 打印
  • @ShekharKhairnar 你是说我正在做的只是收集结果还是我需要收集结果?
  • 您需要收集我在评论中提到的结果,例如double result = 您调用 QBRating 方法的行代码
  • 你知道你在QBRating中使用整数除法吗?
  • 虽然有3个人无法正确投票,但这并不意味着这是一个好问题。请阅读How to Ask 一个好问题。没有问题描述的问题没有帮助。

标签: java methods call instance-variables


【解决方案1】:

您可以为您的 NFLPlayer 类提供每个值的私有字段,而不是向您的方法传递这么多 int 参数(容易混淆):

public class NFLPlayer {

    private final String name;

    private int touchdowns;
    private int passingAttempts;
    private int completedPasses;
    private int passingYards;
    private int interceptions;

    public NFLPlayer(String name) {
        this.name = name;
    }

    // Method names start with a lower case character in Java
    // The name should usually be an imperative 'do something' not a noun ('something')
    // although there are exceptions to this rule (for instance in fluent APIs)
    public double calculateQbRating() {                
        double a = (completedPasses / passingAttempts - 0.3) * 5.0;
        double b = (passingYards / passingAttempts - 3.0) * 0.25;            
        // an AritmeticException will occur if passingAttempts is zero
        double c = (touchdowns / passingAttempts) * 25.0;
        double d = 2.375 - (interceptions / passingAttempts * 25.0);
        return ((a + b + c + d) / 6.0) * 100.0;
    }       

    public String getName() {
        return  name;
    }

    // setter for the touchdowns field
    public void setTouchdowns(int value) {
        touchdowns = value;
    }

    // TODO: add other setters for each private field

    @Override
    public String toString() {
        return String.format("Player %s has QB rating %s", name, calculateQbRating());
    }
}

您的应用程序(这不称为测试):

class NFLApplication {

    public static void main(String[] args) {      

            NFLPlayer playerStats = new NFLPlayer("johnson");    

            playerStats.setTouchdowns(2);
            playerStats.setPassingAttempts(44);
            playerStats.setPassingYards(285);
            playerStats.setInterceptions(1);
            playerStats.setCompletedPasses(35);

            double qbRating = playerStats.calculateQbRating();    

            System.out.println(qbRating);
        }
}

使用 JUnit 框架对您的 NFLPlayer 类进行测试(JUnit 通常默认包含在您的 IDE 中):

public class NFLPlayerTest {

    // instance of the class-under-test
    private NFLPlayer instance;

    // set up method executed before each test case is run
    @Before
    public void setUp() {
        instance = new NFLPlayer(); 
    }

    @Test
    public void testCalculateQbRatingHappy() {
        // SETUP
        instance.setTouchdowns(2);
        instance.setPassingAttempts(44);
        instance.setPassingYards(285);
        instance.setInterceptions(1);
        instance.setCompletedPasses(35);

        // CALL
        double result = playerStats.calculateQbRating();  

        // VERIFY
        // assuming here the correct result is 42.41, I really don't know
        assertEquals(42.41, result);
    }

    @Test
    public void testCalculateQbRatingZeroPassingAttempts() {
        // SETUP
        // passingAttempts=0 is not handled gracefully by your logic (it causes an ArithmeticException )
        // you will probably want to fix this 
        instance.setPassingAttempts(0);

        // CALL
        double result = playerStats.calculateQbRating();  

        // VERIFY
        // assuming here that you will return 0 when passingAttempts=0
        assertEquals(0, result);
    }
}

这个测试类应该放在你的测试源目录中(通常在yourproject/src/test/yourpackage/)。它需要一些导入,这些导入应该可以在 IDE 中轻松解析,因为 JUnit 通常默认情况下可用。

要运行测试,请右键单击它并选择“运行测试”、“测试文件”等内容,具体取决于您使用的 IDE(IDE 是 Eclipse、NetBeans 或 IntelliJ 等开发工具)。您应该会看到一些测试输出,指示测试是成功(绿色)还是失败(红色)。进行此类测试很有用,因为它迫使您思考您的设计并编写更好的代码。 (可测试的代码通常比难以测试的代码更好)并且因为它会在新更改导致现有代码中的错误(回归)时向您发出警告。

编辑:

要创建两个具有不同统计数据的玩家,您必须创建两个实例(我添加了一个name 字段,以便我们更容易区分玩家):

NFLPlayer player1 = new NFLPlayer("adams");
NFLPlayer player2 = new NFLPlayer("jones");

并给他们每个人自己的统计数据:

player1.setTouchdowns(2);
player1.setPassingAttempts(4);
player1.setPassingYards(6);
player1.setInterceptions(8);
player1.setCompletedPasses(10);

player2.setTouchdowns(1);
player2.setPassingAttempts(3);
player2.setPassingYards(5);
player2.setInterceptions(7);
player2.setCompletedPasses(9);

您甚至可以创建一个玩家列表:

List<NFLPlayer> players = new ArrayList<>();
players.add(player1);
players.add(player2);

然后您可以循环打印出所有玩家评分:

for(NFLPlayer player : players) {
    // this uses the `toString` method I added in NFLPlayer
    System.out.println(player);
}

【讨论】:

  • 由于我在网上做所有事情,这有助于我更好地理解如何设置一个完整的程序。我正在为最终将成为具有不同统计数据的多个玩家创建框架。通过使用“set.Touchdowns(2);”等等。这只是一个测试?或者我还能为不同的玩家应用不同的统计数据吗?
  • 'player1.setTouchdowns(2)' 将 player1 的达阵数设置为 2。您可以为不同的玩家设置不同的值,也可以更改玩家的值。
【解决方案2】:

您不应在 SOP 中调用方法名称,而应改为 System.out.println(playerStats.QBRating(touchdowns, passingAttempts, completedPasses, 传球码,拦截)); 或覆盖类中的 toString() 方法并将方法调用分配给局部变量并打印值。 也使用一些框架(Junit)而不是编写存根

【讨论】:

  • 感谢您的快速反馈。我对这一切都很陌生,所以非常感谢。什么是(Junit)框架?当您说覆盖字符串时,您的意思是在我的 NFLPlayer 类中创建一个字符串方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-06
  • 2022-06-19
  • 2014-07-20
  • 1970-01-01
  • 2021-03-12
  • 1970-01-01
相关资源
最近更新 更多