spring - 使用 Spring 运行 JUnit 测试时为空服务

标签 spring testing junit spring-security autowired

我正在开发一个 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);

我可以看到 ServiceNull

在我的 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/

相关文章:

java - 在 JSP/Spring 中禁用内容安全策略

Spring 的 WebUtils.getSessionMutex(javax.servlet.http.HttpSession) 和 HttpSessionMutexListener 仍然相关

java - 将多个 Maven 项目组合成一场 war

java - Mockito:方法的返回值取决于调用的其他方法

java - 带有 Jacoco 插件的 build.gradle 不会为集成测试生成覆盖率报告

mysql - 酒店预订申请 客房供应情况

javascript - 构建接受文件上传并在其上运行测试的 Node JS 应用程序

android - 如何使用 appium 获取已经运行的应用程序的上下文?

testing - 测试 Google 表格插件

unit-testing - 如何包含注释处理器生成的代码来测试 Java/Kotlin 中的类路径