【问题标题】:Spring MVC: ServletContext in JUnit Test?Spring MVC:JUnit 测试中的 ServletContext?
【发布时间】:2015-06-18 14:52:52
【问题描述】:

由于我是 Spring MVC 新手,请帮助我减少困惑。

我有这个服务,需要为它写一个单元测试:

public class SendEmailServiceImpl implements SendEmailService {

private final static Logger logger = LoggerFactory.getLogger(SendEmailServiceImpl.class);

@Autowired
private JavaMailSender mailSender;

public void sendEmail(String id) {

    logger.info("Preparing the mail");

    String mailFrom = Config.getProperty("email.from");
    ...
    }
}

所以这个 sendEmail-Method 使用了静态方法Config.getPropertyConfig 类在 Servlet init()-method 中初始化:

import java.io.File;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;

public class ConfigLoader extends HttpServlet {

    private static final long serialVersionUID = 923456796732565609L;

    public void init() {

            String configPath = getServletContext().getInitParameter("ConfigPath");

            Config.init(configPath);
            System.setProperty("org.owasp.esapi.resources", configPath + "/conf");

        cleanupDirectories(getServletContext());

    }
}

所以最后,对于我的 sendEmail() 方法的测试用例,我需要访问 servlet 上下文。 给出official docs 我的印象是@ContextConfiguration@WebAppConfiguration 注释可以解决我的问题。所以我的单元测试看起来像:

import javax.servlet.ServletContext;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import SendEmailService;

@WebAppConfiguration("file:application/webapp")
@ContextConfiguration("file:application/webapp/WEB-INF/dispatcher-servlet.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class SendEmailServiceImplTest {

    @Autowired
    private SendEmailService sendEmailBean;

    @Autowired
    ServletContext context;

    @Test
    public void sendMail() throws Exception {
        sendEmailBean.sendEmail("b884d8eba6b2438e8e3ee37a69229c98");
    }
}

但不幸的是,从未调用过 Config.init(configPath);,这意味着尚未加载 ServletContext。

我会在这里遗漏什么......?

【问题讨论】:

  • 很确定你会想要使用mocking framework。您将模拟 ServletContext 以获得您想要的行为。

标签: java spring spring-mvc servlets junit


【解决方案1】:

服务不应该依赖于 web 层,你应该有两个应用程序上下文:一个用于服务,一个用于 web,并且只使用服务的测试(服务)。您有一个不应该存在的依赖项,服务代码有效,因为您在发送时获得了属性,但在初始化时服务无法访问该属性,因为它仍然必须由 init-servlet 配置。

您应该在服务应用程序上下文中创建一个 bean,而不是从 Servlet 初始化,您可以使用 bean 属性进行配置,而不是使用 init-param。另一种选择是使用服务类本身来保存属性并进行初始配置。

【讨论】:

    猜你喜欢
    • 2012-10-18
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    相关资源
    最近更新 更多