运行 JUnit 测试 Spring 时为空服务
Null Service while running JUnit test with Spring
我正在开发一个 JUnit 测试到一个 Spring Controller 中,Controller 调用了一堆 Services。我的 JUnit 测试代码如上:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebApplicationConfiguration.class, DatabaseConfiguration.class, ServiceConfiguration.class})
@WebAppConfiguration
public class ProcessFileControllerTest {
private MockMvc mockMvc;
@Test
public void getPageTest() throws Exception{
final ProcessFileController controller = new ProcessFileController();
SecurityHelperUtility.setupSecurityContext("user", "pass", "ROLE_ADMIN");
mockMvc = standaloneSetup(controller).build();
mockMvc.perform(get(URI.create("/processFile.html")).sessionAttr("freeTrialEmailAddress", "")).andExpect(view().name("processFile"));
}
当我 运行 JUnit 测试时,当我调用 ProcessFileController.java
的这一特定代码行时,我得到一个 NullPointerExcelption
final Company company = companyService.getCompanyByUser(userName);
我可以看到 Service
是 Null
。
在我的 ProcessFileController.java
中,Service
声明为:
@Autowired
private CompanyService companyService;
有线索吗?提前致谢。
您正在使用 new 关键字创建控制器。它应该是一个 spring 托管 bean,供 spring 注入其依赖项。使用 @Autowired
@Autowired
ProcessFileController controller;
我正在开发一个 JUnit 测试到一个 Spring Controller 中,Controller 调用了一堆 Services。我的 JUnit 测试代码如上:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebApplicationConfiguration.class, DatabaseConfiguration.class, ServiceConfiguration.class})
@WebAppConfiguration
public class ProcessFileControllerTest {
private MockMvc mockMvc;
@Test
public void getPageTest() throws Exception{
final ProcessFileController controller = new ProcessFileController();
SecurityHelperUtility.setupSecurityContext("user", "pass", "ROLE_ADMIN");
mockMvc = standaloneSetup(controller).build();
mockMvc.perform(get(URI.create("/processFile.html")).sessionAttr("freeTrialEmailAddress", "")).andExpect(view().name("processFile"));
}
当我 运行 JUnit 测试时,当我调用 ProcessFileController.java
NullPointerExcelption
final Company company = companyService.getCompanyByUser(userName);
我可以看到 Service
是 Null
。
在我的 ProcessFileController.java
中,Service
声明为:
@Autowired
private CompanyService companyService;
有线索吗?提前致谢。
您正在使用 new 关键字创建控制器。它应该是一个 spring 托管 bean,供 spring 注入其依赖项。使用 @Autowired
@Autowired
ProcessFileController controller;