I have the following controller:
@Controller
public class HomeController {
@Resource(name="returnGraph")
Graph returnGraph;
@RequestMapping("/")
public String goToHomePage(HttpSession session){
session.setAttribute("sm", returnGraph.getVertexes());
return "home";
}
}
I tried the following j unit test but it didnt work:
public class HomeControllerTest {
@Mock
Graph returnGraph;
@Mock
Map<String,Vertex> vertexes;
@Mock
HttpSession session;
HomeController homeController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
homeController = new HomeController();
}
@Test
public void testgoToHomePage(){
when(returnGraph.getVertexes()).thenReturn(vertexes);
assertEquals("home", homeController.goToHomePage(session));
}
}
It says I have null pointer exception at.
session.setAttribute("sm", returnGraph.getVertexes());
However I am not sure why? I am not sure what more I can do about this, how exactly do I deal with the session.setAttribute.
You may try the Spring MVC Test Framework, here is the documatation:
You can test your controller like this:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public abstract class HomeControllerTest {
@Autowired
protected WebApplicationContext context;
@Resource(name="returnGraph")
Graph returnGraph;
protected MockMvc mockMvc;
@Test
public void testgoToHomePage(){
this.mockMvc.perform(get("/")
.andExpect(status().isOk())
.andExpect(content().string("home"));
}
}
@RunWith(SpringJUnit4ClassRunner.class)
public class HomeControllerTest {
@Mock
Graph returnGraph;
@Mock
Map<String,Vertex> vertexes;
@Mock
HttpSession session;
@InjectMocks
HomeController homeController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testgoToHomePage(){
when(returnGraph.getVertexes()).thenReturn(vertexes);
assertEquals("home", homeController.goToHomePage(session));
}
}
You have to use these annotations: @RunWith(SpringJUnit4ClassRunner.class)
, @WebAppConfiguration
If using JavaConfig: @ContextConfiguration(classes = MyWebConfig.class)
A complete working example : http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/spring-mvc-unit-testing/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.