您的位置:首页 > 编程语言 > Java开发

Java Unit Testing with JUnit in NetBeans

2016-05-28 08:39 531 查看
Getting started....

Method 1:



Go to menu->File->New File:



Select Test for Existing Class:



Untick most of the check boxes:



The testing class automatically generated:



/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package humanresources.businessdomain;

import org.junit.Test;
import static org.junit.Assert.*;

/**
*
* @author Vincent
*/
public class PaymentMethodOptionTest {

public PaymentMethodOptionTest() {
}

@Test
public void testValues() {
}

@Test
public void testValueOf() {
}

@Test
public void testGetDisplayName() {
}

@Test
public void testFromString() {
}

}


JUnit knows to execute the test method as a test because it's marked with the @Test annotation. You can have other methods in the test class that are not tests, and JUnit doesn't try to execute them as such.
JUnit creates one test method for each method of the target class in the test class, plus two more methods: testValues() and testValueOf(), which are inherited from enum. Their name—an important piece of information—default
to testMethodName.

Fill in the test methods:

public void testGetDisplayName() {
// Arrange
PaymentMethodOption myCashOpt = PaymentMethodOption.CASH;
PaymentMethodOption myCreditOpt = PaymentMethodOption.CREDITCARD;
// Act
String actualResultCash = myCashOpt.getDisplayName();
String actualResultCredit = myCreditOpt.getDisplayName();
// Assert
assertThat(actualResultCash, equalTo("Cash"));
assertThat(actualResultCredit, equalTo("Credit card"));
}


Run the test java file:



And you will get a prompt:



Click it to open TestResults Window:



What shall we test against?

package iloveyouboss;

import java.util.*;

public class Profile {
private Map<String,Answer> answers = new HashMap<>();
private int score;
private String name;

public Profile(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void add(Answer answer) {
answers.put(answer.getQuestionText(), answer);
}

public boolean matches(Criteria criteria) {
score = 0;

boolean kill = false;
boolean anyMatches = false;
for (Criterion criterion: criteria) {
Answer answer = answers.get(
criterion.getAnswer().getQuestionText());
boolean match =
criterion.getWeight() == Weight.DontCare ||
answer.match(criterion.getAnswer());

if (!match && criterion.getWeight() == Weight.MustMatch) {
kill = true;
}
if (match) {
score += criterion.getWeight().getValue();
}
anyMatches |= match;
}
if (kill)
return false;
return anyMatches;
}

public int score() {
return score;
}
}


After reading the above code, the author points out there are 15 points we may want to test:

The point is, we would write fewer tests in the reality, so, how to narrow down the tests?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java jnuit