编写JUnit测试 [英] Writing JUnit Tests
问题描述
请,我是Java新手.如何为以下程序编写JUnit测试:
Please, I am new to Java. How can I write a JUnit test for the program below:
要测试的程序:
package codekeeper;
/**
*
* @author henryjoseph
*/
import java.util.*;
import java.io.*;
public class CodeKeeper {
ArrayList<String> list; //no specific amount..
String[] codes = {"alpha","lambda","gamma","delta","zeta"};
public CodeKeeper (String[] userCodes)
{
list = new ArrayList<String>();
for(int i =0; i<codes.length;i++)
addCode(codes[i]);
for(int i =0; i<userCodes.length;i++)
addCode(userCodes[i]);
for(String code:list)
System.out.println(code);
}
final void addCode(String code)
{
if(!list.contains(code))
list.add(code);
}
public static void main(String[] args) {
System.out.print("Enter your name and press Enter: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = null;
String[] argu = new String[] {name};
try {
name = br.readLine();
argu = new String[] {name} ;
}catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
CodeKeeper keeper = new CodeKeeper(argu);
}
}
示例测试代码:
public class MyClassTest {
@Test
public void testMultiply() {
MyClass tester = new MyClass();
assertEquals("Result", 50, tester.multiply(10, 5));
}
}
这是编写Junit测试的标准方法吗?
Is this a standard way of writing the Junit Tests?
推荐答案
首先是一些背景,然后是一些示例.当针对代码编写单元测试时,您正在测试应用程序的非常特定且有限的情况.这意味着每个单元测试最多应涵盖功能(方法)可以接收的一(1)种情况.如果要一起测试多个功能,则将执行集成测试.现在,如果我们采用您已声明的以下函数:
Some background first then some examples. When you write unit tests against your code you are testing a very specific and finite case of your application. What that means is that each unit test should cover at most one (1) scenario that a function (method) can receive. If you want to test multiple functions together you would be performing integration testing. Now if we take the following function that you have declared:
final void addCode(String code)
{
if(!list.contains(code))
list.add(code);
}
假定codeKeeper
已正确初始化.
适当的单元测试如下所示:
Assume that codeKeeper
is properly initialized.
An appropriate unit test would look like this:
@Test(expected= NullPointerException.class)
public void testAddCode_1() throws Exception
{
codeKeeper.addCode(null);
}
另一个合适的用法如下:
Another appropriate usage is the following:
@Test()
public void testAddCode_2() throws Exception
{
codeKeeper.addCode("myMagicCode");
assertTrue(codeKeeper.getList().contains("myMagicCode");
}
这篇关于编写JUnit测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!