Java JUnit测试类
这是我第一次不得不写一个J单元测试,我被困在了如何开始的问题上。此类表示Otherlo板上的单个单元,它具有网格和令牌值 我想用“黑”和“白”以及不同的位置来测试构造函数,我还想测试所有的setter和getter 任何帮助都将不胜感激Java JUnit测试类,java,junit,Java,Junit,这是我第一次不得不写一个J单元测试,我被困在了如何开始的问题上。此类表示Otherlo板上的单个单元,它具有网格和令牌值 我想用“黑”和“白”以及不同的位置来测试构造函数,我还想测试所有的setter和getter 任何帮助都将不胜感激 public class BoardCell { /** * The Item at this BoardCell. */ private Item token; /** * The CellLocatio
public class BoardCell
{
/**
* The Item at this BoardCell.
*/
private Item token;
/**
* The CellLocation of this BoardCell.
*/
private BoardLocation location;
/**
* Constructor.
* @param row the row number.
* @param col the column number.
* @param token the Item value.
*/
public BoardCell(int row, int col, Item token)
{
this.token = token;
location = new BoardLocation(row, col);
}
/**
* Sets the Item value.
* @param token the Item value.
*/
public void setItem(Item token)
{
this.token = token;
}
/**
* Set the value of the Item in this BoardCell.
* @param val the value of the Item.
*/
public void setValue(String val)
{
this.token.setValue(val);
}
/**
* Gets the Item value.
* @return the Item at this BoardCell.
*/
public Item getItem()
{
return token;
}
/**
* Get the BoardLocation for this BoardCell.
* @return the BoardLocation for this BoardCell.
*/
public BoardLocation getLocation()
{
return location;
}
}
最好从上的信息和一些教程开始。此外,最佳实践是先编写测试,然后编写它正在测试的函数。也就是说,这里有一个大致的轮廓: 1) 列出你想要的测试列表。关注每项功能及其不同的使用方式(以及可能出错的方式) 2) 编写将预期行为与实际行为进行比较的测试,如下所示:
@Before
public void setUp() {
// In this function you'll want to create instances of the class that you will then test
}
@Test
public void testSomething() {
assertEquals(BoardCell.getItem(), whatever you think it should equal); //or whatever you're testing
}
@Test
public void etcetera() . . .
您需要首先创建一个新类来保存所有不同的测试,您可以调用它,例如,
BoardCellTest
或BoardCellTestCase
在这个类中,您需要添加不同的测试用例,它们是用@test
注释的公共void
方法
然后,通过创建正确的
BoardCell
对象并获取它们的值,或者设置新的值,每个方法都应该断言(使用assert
类中的方法)您需要测试的内容。您是在寻找代码覆盖率,还是只是想看看某个方法是否按照您的预期方式工作?如果您只是在寻找覆盖率,那么只需创建一个类并使用@Test
注释方法,大多数覆盖率工具将获取JUnit/Surefire报告并对其进行适当的解释
如果您希望测试getter或setter之类的东西,那么可以使用简单的断言测试
@测试
public void testGetItem()引发异常{
Item Item=新的BlackItem();
BoardCell=新的BoardCell(128、256,项目);
assertNotNull(“项不应为null”,cell.getItem());
assertEquals(“项目应被视为相等”,item,cell.getItem());
}
如果您在类中重写toString
,那么JUnit将轻松打印toString
的结果,如果断言失败,这对于assertEquals
、assertarayequals
(我相信)和assertThat
都是如此。我手头没有一份例外情况的准确副本,但它将与以下内容大致相同:
org.junit.AssertionError:应为项{name=“Black Item”},但为项{name=“White Item”}
应为:项{name=“Black Item”}
实际:项目{name=“White Item”}
用于测试
BoardLocation
和Item
对象是否相等的东西。阅读更多断言的好地方是JUnit站点,正如其他海报所提到的,我个人更喜欢它。您使用IntelliJ吗?如果是这样,请尝试高亮显示BoardCell并按住Shift-Ctrl-T。它将为您构建一个测试。为什么不使用assertEquals?当对象不相等时,它提供更好的输出(假设您重写toString
方法)