2010-07-27 117 views
0

我正在使用junit 4.8.1。Junit @Before注解给出Nullpointer异常

以下是代码。我正在得到“Nullponiter”例外。我怀疑在@Before下的“SetUp”代码在其他方法之前没有被执行过。要求有学问的朋友帮助我解决问题。 (这是由Koskela 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()); 
} 

} 

回答

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}"); 
+0

非常感谢非常快速的答复。有效。 Registers Anand – Anand 2010-07-29 09:52:06

+0

所以你可以接受答案;-) – djna 2010-07-29 18:30:47