更喜欢使用模拟和单元测试助手进行弹簧测试:
模拟服务替换了多个依赖项
@Controller
@RequestMapping("/people")
public class PeopleController {
@Autowired
protected PersonService personService;
@GetMapping
public ModelAndView people(Model model) {
for (Person person: personService.getAllPeople()) {
model.addAttribute(person.getName(), person.getAge());
}
return new ModelAndView("people.jsp", model.asMap());
}
}
私人MockMvc模拟Mvc:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PeopleControllerTest {
@Autowired
PersonService personService;
private MockMvc mockMvc;
@Configuration
static class Config {
// Other beans
@Bean
public PersonService getPersonService() {
return mock(PersonService.class);
}
}
@Test
public void testPeople() throws Exception {
// When
ResultActions actions = mockMvc.perform(get("/people"));
}
}
我想运行mockMvc
java.lang.NullPointerException
答案 0 :(得分:0)
从源代码中,我看到mockMvc没有任何值,这就是为什么它在此代码行中命中“ java.lang.NullPointerException”:
ResultActions actions = mockMvc.perform(get("/people"));
要使其运行,我认为首先需要赋予嘲笑价值。
通过构造函数:
@Test
public void testPeople() throws Exception {
mockMvc = new MockMvc();
// When
ResultActions actions = mockMvc.perform(get("/people"));
}
或自动接线:
@Autowired
MockMvc mockMvc
取决于MockMvc类的目的
答案 1 :(得分:0)
这是因为您从未在代码中初始化mockMvc
,而访问它的时间点将导致nullPointerException
。您需要在使用它之前对其进行初始化,并且由于类中的多个测试可能正在使用它,所以最好的方法是使用setup()
注释的@before
方法。请尝试以下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PeopleControllerTest {
@Autowired
PersonService personService;
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
@Configuration
static class Config {
// Other beans
@Bean
public PersonService getPersonService() {
return mock(PersonService.class);
}
}
@Test
public void testPeople() throws Exception {
// When
ResultActions actions = mockMvc.perform(get("/people"));
}
}
答案 2 :(得分:0)
执行以下步骤:
创建服务模拟而不是原始服务 (“ PersonServiceMock”)
通过服务模拟替换原始服务
@Autowired
PersonService personService;
@Autowired
PeopleController peopleController;
private MockMvc mockMvc;
@Before
public void setup() {
peopleController = new PeopleController(new personServiceMock());
mvc = MockMvcBuilders.standaloneSetup(peopleController).build();
}
@Configuration
static class Config {
// Other beans
@Bean
public PersonService getPersonService() {
return mock(PersonService.class);
}
}
@Test
public void testPeople() throws Exception {
// When
ResultActions actions = mockMvc.perform(get("/people"));
}
}