java - 为类编写简单的电子表格处理器。 Location 类的方法未通过单元测试。有什么帮助吗?

标签 java string unit-testing integer spreadsheet

为一个类编写一个程序,我有执行此操作的规范:一个完全实现 Location 接口(interface)的类,并包含一个采用单个字符串参数(例如“D20”)的构造函数。我的类(class)是

package textExcel;

//Update this file with your own code.

public class SpreadsheetLocation implements Location
{
String Loc;
private int col = Integer.parseInt(Loc.substring(1, 2));
private int row = Integer.parseInt(Loc.substring(0, 0));
@Override
public int getRow()
{
    System.out.println(row);
    // TODO Auto-generated method stub
    return row;
}

@Override
public int getCol()
{
    System.out.println(col);
    // TODO Auto-generated method stub
    return col;
}

public SpreadsheetLocation(String cellName)
{
    Loc = cellName;

}

}

界面是

 public interface Location
 {
// represents a location like B6, must be implemented by your SpreadsheetLocation class
int getRow(); // gets row of this location
int getCol(); // gets column of this location
 }

单元测试是

public void testLongShortStringCell()
    {
        SpreadsheetLocation loc = new SpreadsheetLocation("L20");
        assertEquals("SpreadsheetLocation column", 11, loc.getCol());
        assertEquals("SpreadsheetLocation row", 19, loc.getRow());

        loc = new SpreadsheetLocation("D5");
        assertEquals("SpreadsheetLocation column", 3, loc.getCol());
        assertEquals("SpreadsheetLocation row", 4, loc.getRow());

        loc = new SpreadsheetLocation("A1");
        assertEquals("SpreadsheetLocation column", 0, loc.getCol());
        assertEquals("SpreadsheetLocation row", 0, loc.getRow());
    }

什么可能导致我的代码无法通过单元测试?

最佳答案

您在初始化之前尝试解析 Loc,导致出现 NullPointerException

将解析移至构造函数后,您仍然需要对其进行修复。该列由字母表示,您不能只将其解析为 int - 您需要获得它与 A 之间的区别,在简化的假设下,它只能有一个字符:

public SpreadsheetLocation(String cellName) {
    loc = cellName;
    row = Integer.parseInt(loc.substring(1)) - 1;
    col = loc.charAt(0) - 'A';
}

关于java - 为类编写简单的电子表格处理器。 Location 类的方法未通过单元测试。有什么帮助吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55038145/

相关文章:

java - 将 html 页面更改为 .png

Java JTable 未填充 DefaultTableModel

php - 将 PHP 变量与字符串文字混合

asp.net-mvc - 单元测试 aspx View

unit-testing - Chef 自定义资源的单元测试

java - 如何实现List<SomeParamType>到List<SomeParamType<?>>的转换

java - Spring Cloud Stream Service-Bus Binder的错误 channel

SQL无法连接

java - 根据其自然顺序获取下一个字符串

android - 如何使用 ant 运行 android 库的单元测试?