【问题标题】:I have two methods that need to be tested using the JUnit test. Here are the codes我有两种方法需要使用 JUnit 测试进行测试。这是代码
【发布时间】:2012-12-03 20:31:40
【问题描述】:

公共类 Manager 扩展了 Employee {

/**
 * Manager Constructor takes in arguements and calls superclass
 * @param id
 * @param weeklyPay
 */
public Manager(int id, double weeklyPay) // Constructor
{
    super(id);
    super.weeklyPay=weeklyPay;
}

public String toString() // returns a String
{
    return "Manager "+super.toString();
}

public double calculateWeeklyPay() // calculates weeklypay
{
    return super.weeklyPay;
}

我必须测试 toString 方法和 calculateWeeklyPay 方法。我该怎么做?

【问题讨论】:

    标签: java junit4


    【解决方案1】:

    不确定你想测试这个类,因为你的超类中的逻辑看起来很多。但是这里...

    assertEquals(42d, new Manager(1, 42d).calculateWeeklyPay,0.001);
    

    并测试字符串是否等于(假设super.toString 返回MyString

    assertEquals("ManagerMyString", new Manager(1, 42d));
    

    右侧的toString 会自动调用,或者如果您想显式调用

    assertEquals("ManagerMyString", new Manager(1, 42d).toString());
    

    所有这些方法都是 JUnit 的一部分,可以通过 Assert 类静态导入到您的 java 文件中。

    【讨论】:

    • 感谢您的 calculateWeeklyPay 方法,因为它有效,但您的 to.string 方法未能通过测试。我可以为您提供更多信息,您可能需要修复 tostring 方法吗?
    • Employee 类中的 toString() 会返回什么?
    • andreih 有问题@user1873746。超类中的 toString() 返回什么?我假设 MyString 可能是错误的。
    • @user1873746,将最终断言中的"MyString" 更改为Employee toString() 将返回的内容。
    • public String toString() // toString 方法 { return id+" 的周薪为 "+weeklyPay;这是来自员工的 toString 返回的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    相关资源
    最近更新 更多