Junit @ Перед аннотацией выдается исключение Nullpointer - PullRequest
0 голосов
/ 27 июля 2010

Я использую junit 4.8.1.

Ниже приведен код. Я получаю исключение "Nullponiter". Я подозреваю, что код "SetUp" в @Before не был исключен перед другими методами. Попросите знакомых друзей помочь мне в решении проблемы. (Это пример книги 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());
}

}

1 Ответ

3 голосов
/ 27 июля 2010

У вас есть две переменные с одинаковым именем:

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