【发布时间】: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.getProperty。 Config 类在 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