我正在开发一个 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 关键字创建 Controller 。它应该是一个 spring 管理的 bean,供 spring 注入(inject)它的依赖。使用@Autowired
@Autowired
ProcessFileController controller;
关于spring - 使用 Spring 运行 JUnit 测试时为空服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36847161/