如何编写单元测试? [英] How to write a Unit Test?

查看:120
本文介绍了如何编写单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个执行二进制求和的java类,我仍在试图弄清楚如何进行单元测试,但我不知道该怎么做。我已经用Google搜索了,我得到的最佳解释是来自维基百科的页面: http://en.wikipedia。 org / wiki / Unit_testing

I have a java class that does a binary sum, I am still trying to figure out how to do unit tests but I don't know how to do it. I've googled around and the best explanation I had was the page from Wikipedia: http://en.wikipedia.org/wiki/Unit_testing

但我仍然不确定如何为此程序进行测试。该程序所做的基本上是2字节[]并添加它们并返回新的二进制数组。用Java编写。我该如何测试呢?

but I'm still unsure how to do my test for this program. What the program does is basically take 2 byte[] and add them and return the new binary array. Written in Java. How can I test it?

推荐答案


  1. 定义正常的预期和期望输出案例,输入正确。

  1. Define the expected and desired output for a normal case, with correct input.

现在,通过声明一个类来实现测试,将它命名为任何东西(通常类似于TestAddingModule),并将testAdd方法添加到它(即像一个下面):

Now, implement the test by declaring a class, name it anything (Usually something like TestAddingModule), and add the testAdd method to it (i.e. like the one below) :


  • 写一个方法,在它上面添加@Test注释。

  • In方法,运行你的二进制和和$ code> assertEquals(expectedVal,calculatedVal)。

  • 通过运行方法测试你的方法(在Eclipse,右键单击,选择Run as→JUnit test)。

  • Write a method, and above it add the @Test annotation.
  • In the method, run your binary sum and assertEquals(expectedVal,calculatedVal).
  • Test your method by running it (in Eclipse, right click, select Run as → JUnit test).

//for normal addition 
@Test
public void testAdd1Plus1() 
{
    int x  = 1 ; int y = 1;
    assertEquals(2, myClass.add(x,y));
}


添加其他情况。


  • 如果存在整数溢出,请测试二进制和不会引发意外异常。

  • 测试您的方法是否正常处理空输入(例如下面的例子)。

  • Test that your binary sum does not throw a unexpected exception if there is an integer overflow.
  • Test that your method handles Null inputs gracefully (example below).

//if you are using 0 as default for null, make sure your class works in that case.
@Test
public void testAdd1Plus1() 
{
    int y = 1;
    assertEquals(0, myClass.add(null,y));
}


这篇关于如何编写单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆