java - JUnit 比较字符串

标签 java junit

在 JUnit 上做一些功课。我们必须测试我们所有的方法。我已正确编写了其他 4 个方法并进行了测试,但我遇到了 toString 方法无法正常工作的问题。

//here is my Gps constructor, if needed. I don't think it is, but including it just in case.

public Gps(String n, GpsCoordinates pos)
    {
        super();
        this.name = n;
        this.position = pos;
    }

//Here is my Gps.class toString() method that I want to test.
@Override
public String toString()
    {
        String gps = "myGPS: " + name + ": " + position;
        return gps;
    }

这是我的 JUnit 测试方法:

//Here are my instances in my GpsTest.class

private GpsCoordinates testGpsCoordinates = new GpsCoordinates(40.760671, -111.891122);
private Gps testGps3 = new Gps("TEST3", testGpsCoordinates);

//Here is my toString test method
    @Test
    public void testToString()
        {
            String expected = "myGPS: TEST3: 40.760671, -111.891122";
            assertEquals(expected, testGps3.toString());
        }

所以当我运行这个时,我遇到了 JUnit 失败。我检查了日志,上面写着:

Expected:
myGPS: TEST3: 40.760671, -111.891122

Actual:
myGPS: TEST3: 40.760671, -111.891122

我认为assertEquals可能使用“==”而不是.equals(),但事实并非如此——它确实使用.equals(),所以我没有想法

有人能指出我正确的方向吗?我已经搞砸了 30 分钟了,移动我的实例,重命名东西等等,并且正在抓狂。

cricket_007 要求我添加我的 GpsCooperatives.toString(),这里是:

public String toString()
{
    //formatting this to only return to 6 decimal places. On a separate part
    //of the assignment, we are to add a random double to the GpsCoordinates
    //(like a fake "gps update") and limit it to 6 decimal places.
    DecimalFormat df = new DecimalFormat("####.000000");
    return df.format(latitude) + ", " + df.format(longitude) + "\n";
}

最佳答案

预期值没有“\n”,而 GpsCooperative.toString() 添加了它。

关于java - JUnit 比较字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35306775/

相关文章:

java - 使用 hamcrest 匹配器进行 jUnit 测试 - 如何测试集合的大小。

java - 运行 ant build 得到 "package org.junit does not exist"

java - 模拟服务器请求

Java解析包含字符串映射的Json对象以将字符串映射到字符串数组

Java - 泛型类的类成员的行为

java - 不可转换的类型无法转换

具有两个休眠事务的 spring junit 测试

java - 在运行时重新定义嵌套类,可能吗? (java.lang.NoClassDefFoundError : class names don't match)

java - 在 JVM 运行时查找类

java - 使用仅适用于第一次测试的流进行单元测试日志