我正在尝试运行 Spring MVC 测试,但不断收到此异常。
org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是 java.lang.NullPointerException
发生异常是因为自动装配的依赖,
@Autowired
private AccountService accountService;
没有在测试中注入(在测试之外工作正常)。
谁能帮我这个。这是我的代码:
//AccountControllerITest 类
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class AccountControllerITest {
private MockMvc mvc;
ObjectMapper om;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();
}
@Test
public void getAccounts() throws Exception {
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get("/api/accounts"))
.andExpect(status().isOk())
.andReturn();
}
}
}
//账户控制器
@RestController
@RequestMapping("/api/accounts")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Set<AccountInfo>> getAccounts(@RequestParam(value = "firstName", required = false) String firstName,
@RequestParam(value = "surName", required = false) String surName) {
Set<AccountInfo> accounts = accountService.getAccounts(firstName, surName);
return new ResponseEntity<>(accounts, HttpStatus.OK);
}
}
谢谢您的帮助!