我正在尝试运行Spring MVC测试但仍然遇到此异常。
org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是java.lang.NullPointerException
由于自动连接的依赖项
,因此发生了异常 @Autowired
private AccountService accountService;
没有被注入测试(在测试之外工作正常)。
任何人都可以帮助我。这是我的代码:
// AccountControllerITest Class
@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();
}
}
}
//的AccountController
@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);
}
}
感谢您的帮助!
答案 0 :(得分:1)
因为您使用的是独立设置:mvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();
。如果您通过new AccountController()
创建控制器,则Spring没有机会注入accountService
,因为它不控制实例创建和连线。
您有两种选择:
将测试切换到单元测试,不要使用SpringJUnit4ClassRunner
或MockServletContext
所有。您可以使用@InjectMocks
注入私人accountService
:
public class AccountControllerITest {
private MockMvc mvc;
ObjectMapper om;
@Mock
private AccountController accountController = new AccountController();
@InjectMocks
private AccountService accountService = new Mockito.mock(AccountService.class);
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
您还可以对控制器应用增强功能。使用构造函数注入替换字段注入,您可以通过测试中的构造函数将accountService
传递给控制器。这样您根本不需要使用@InjectMocks
。
使用webAppContext设置:
@Autowired
private WebApplicationContext webApplicationContext;
@BeforeMethod
public void init() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
答案 1 :(得分:1)
您需要配置测试以注入自动装配的属性。请参阅以下代码块:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class AccountControllerITest {
// ... your test code
@Configuration
public static class YourConfiguration {
@Bean
AccountService accountService() {
// init and return your AccountService
}
}
}
您可以使用Mockito初始化AccountService
。