有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java“简单”Spring单元测试

我正在尝试为一个继承的基于Spring的项目配置单元测试。我已经尝试了一些方法,但基本上我一直在尝试将@Autowired内容添加到我的测试用例中。以下是我的设置:

控制器类如下所示:

@Controller("serverService")
@RequestMapping("/rest/server")
@Api(value = "server")
public class ServerServiceImpl extends AbstractServiceImpl implements ServerService {
    @Override
    @RequestMapping(value = "/getTime", method = RequestMethod.GET)
    public @ResponseBody
    GatewayResponse<TimeData> getTime() {...}

ServerService只是一个支持与GWT互操作的接口。我现在不太担心来自GWT的单元测试

AbstractServiceImpl的主要目的是包装一个基于SOAP的web服务,该服务器本质上是代理的,使移动友好。web服务由Apache CXF自动生成AbstractServiceImpl大致如下:

public class AbstractServiceImpl {
    @Autowired
    private WebServices webServices;

    public WebServices getWebServices() {
        return webServices;
    }

在我的测试课上,我有:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:**/applicationContext.xml", "classpath:**/applicationContext-Services.xml"})
@WebAppConfiguration
public class LoginTest {
    @Autowired
    private ServerServiceImpl svc;

    public LoginTest() {
    }

    @Test
    public void validate() {
        assertNotNull(svc);
    }
}

我没有兴趣尝试用模拟JSON之类的东西来创建对我的web服务的模拟调用。我只想编写单元测试,用未模拟的WebServices对象创建未模拟的ServerServiceImpl,并调用实时服务器

我的测试目前失败,因为@Autowired无法创建ServerServiceImpl。我还尝试过重构代码,对WebServices使用@Autowired,并将其传递给ServerServiceImpl的构造函数,但由于@Autowired的原因,这也失败了


共 (1) 个答案

  1. # 1 楼答案

    事实证明这非常简单。如果为应用程序上下文指定不存在的路径,Spring将抛出错误,例如:

    @ContextConfiguration("classpath:does-not-exist.xml")
    

    上面将创建一条简单的错误消息,告诉您问题所在,即文件未找到异常。另一方面,该代码不会:

    @ContextConfiguration("classpath:**/does-not-exist.xml")
    

    所以我的问题只是Spring找不到应用程序上下文XML。最终,我复制了一份live context,将其放入src/test/resources,并更新了我的pom.xml@ContextConfiguration,如下所示:

    <addtionalClasspathElements>
        <addtionalClasspathElement>${basedir}/src/test/resources</addtionalClasspathElement>
    </addtionalClasspathElements>
    
    @ContextConfiguration(locations = { "classpath:applicationContext.xml", "classpath:applicationContext-Services.xml" })