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

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

问题描述

我有一个 Java 课程.我如何单元测试?

I have a Java class. How can I unit test it?

在我的例子中,我有类做一个二进制和.它需要两个 byte[] 数组,将它们相加,然后返回一个新的二进制数组.

In my case, I have class does a binary sum. It takes two byte[] arrays, sums them, and returns a new binary array.

推荐答案

  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 注解.
  • 在该方法中,运行二进制和和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));
}

根据需要添加其他案例.

Add other cases as desired.

  • 如果存在整数溢出,请测试您的二进制和不会引发意外异常.
  • 测试您的方法是否优雅地处理 Null 输入(下面的示例).

  • 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天全站免登陆