我正在使用junit 4.8.1。
以下是代码。我得到“Nullponiter”例外。我怀疑@Before
下的“SetUp”代码在其他方法之前没有被删除。请求有学问的朋友帮我解决问题。 (这是科斯克拉的TDD书的一个例子)
import org.junit.*;
import java.util.*;
import static org.junit.Assert.*;
public class TestTemplate {
private Template template;
@Before
public void setUp() throws Exception{
Template template = new Template("${one},${two},${three}");
template.set("one","1");
template.set("two","2");
template.set("three","3");
}
@Test
public void testmultipleVariables() throws Exception{
testassertTemplateEvaluatesTo("1, 2, 3");
}
@Test
public void testUnknownVariablesAreIgnored() throws Exception{
template.set("doesnotexist","whatever");
testassertTemplateEvaluatesTo("1, 2, 3");
}
private void testassertTemplateEvaluatesTo(String expected){
assertEquals(expected,template.evaluate());
}
}
答案 0 :(得分:3)
您有两个具有相同名称的变量:
private Template template;
@Before
public void setUp() throws Exception{
// declaring second variable here
Template template = new Template("${one},${two},${three}");
将最后一行更改为:
template = new Template("${one},${two},${three}");