【问题标题】:JUnit Test cases Run with tomcat container or JVMJUnit 测试用例 使用 tomcat 容器或 JVM 运行
【发布时间】:2015-12-29 04:57:54
【问题描述】:

我正在为我的 Spring 应用程序编写 JUnit 测试用例。我在 eclipse 中使用 codepro 工具来生成测试用例。当我运行这个测试用例时,它是在 JVM 上而不是在 Tomcat 服务器上运行的。所以我想知道它如何在服务器上运行?在 JVM 或 tomcat 上运行测试用例的最佳实践是什么?为什么?所以请建议我。代码如下。

import java.io.InputStream;
import java.util.Properties;

import javax.servlet.http.HttpSession;

import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.ContextConfiguration; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zodiacapi.framework.business.ZodiacMobileBusinessTx;
import com.zodiacapi.framework.controller.ZodiacMobileAPIController;
import com.zodiacapi.framework.delegate.SendNotificationDelegate;
import com.zodiacapi.framework.dto.ReturnAPIMessageDTO;
import com.zodiacapi.framework.dto.UserDTO;
import com.zodiacweb.framework.cache.CacheService;
import com.zodiacweb.framework.cache.EhCacheServiceImpl;
import com.zodiacweb.framework.exception.ZodiacWebException;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:applicationContext.xml" })
public class ZodiacMobileAPIControllerTest extends TestCase {

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

@Autowired
private ZodiacMobileBusinessTx zodiabMobileBusinessTx;

public ZodiacMobileBusinessTx getZodiabMobileBusinessTx() {
    return zodiabMobileBusinessTx;
}
@Test
public void testMobileLogin_1()
    throws Exception {
    ReturnAPIMessageDTO entities = new ReturnAPIMessageDTO();
    Properties prop = new Properties();
    InputStream in = getClass().getResourceAsStream("login.properties");
    prop.load(in);

    try{
    UserDTO result = zodiabMobileBusinessTx.login(prop.getProperty("username"), prop.getProperty("password"), prop.getProperty("apikey"), prop.getProperty("deviceid"), prop.getProperty("deviceModel"));


    System.out.println("result of test"+result);

} catch (ZodiacWebException e) {
    logger.error("Internal Server Error fetching user info", e);
    entities.setStatus("false");
    entities.setMessage(e.getMessage());
    entities.setVersion("");

} catch (Throwable t) {

    entities.setStatus("false");
    entities.setMessage(t.getMessage());
    entities.setVersion("");
}

}

}

【问题讨论】:

    标签: java tomcat junit


    【解决方案1】:

    对于单元测试,您通常会在 JVM 中执行它。您可能只会在服务器中运行的应用程序上执行集成/功能测试。

    测试 Spring 控制器的选择(我熟悉的)是:

    1. 将控制器作为容器和服务器之外的常规 POJO 进行测试 例如:MyController controller = new MyController())
    2. 使用 Spring Test MVC 测试控制器。这实际上会在您的测试期间启动 Spring。(我更喜欢这个选项)有关一些示例,请参阅 Unit Test Spring Controllers
    3. 如果您想在真实的 tomcat 实例中测试您的应用程序,您可以使用 ArquillianThe Arquillian Spring Extension。就学习曲线而言,最后一个选项绝对是最复杂的。但很高兴知道。(我自己还没有成功地将它与 Spring 应用程序一起使用)

    【讨论】:

    • 我的测试类是我的应用程序的控制器。你需要看代码吗?
    • 是的,因为可以在tomcat内部和外部测试Spring Controller。
    • 我已经编辑了我的帖子以尝试概述您可用于测试 Spring 控制器的选项。
    • 我曾尝试使用 @RunWith(Arquillian.class) 而不是 @RunWith(SpringJUnit4ClassRunner.class) 但我认为构建路径中缺少它的 jar 文件,这就是它为我抛出错误的原因。因此,如果您知道使用哪个 jar 文件,请建议我。
    • Logback 允许你像这样在配置文件中使用变量: ${USER_HOME}/myApp.log 这有帮助吗?
    【解决方案2】:

    暂时不用担心使用 Arquillian ......这需要一些时间来学习。

    有关测试弹簧控制器的工作示例,请参阅下面的代码。我从您的代码示例中注意到您没有所有正确的注释和初始化方法。

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes = App.class)
    @TestPropertySource(locations = "classpath:test.properties")
    @WebAppConfiguration
    public class AdminUserControllerUnitTest {
    
    MockMvc mvc;
    
    @Autowired
    WebApplicationContext webApplicationContext;
    
    
    
    @Before
    public void initialize(){
    
        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
    
    
    @Test
    public void testListUsers() throws Exception {
    
        Account account = new Account();
        account.setId(1l);
    
        mvc.perform(
                    get("/admin/user")
                            .sessionAttr("account",account)                     
                   );
                    .andExpect(MockMvcResultMatchers.model().attribute("users",hasSize(4)));
    
    
    }
    

    【讨论】:

    • 不,我认为它使用了某种模拟 servlet 容器。为什么要专门在tomcat中测试呢?如果您需要走那条路,请查看codewithzenmind.wordpress.com/2013/09/20/…
    • 我想在服务器中运行它,因为我想要 Junit 测试用例和应用程序日志的单独日志。我正在使用 logback.xml。在 logback.xml 中,我使用“catalina.home”服务器变量来提供日志文件路径。现在当我运行测试用例时,它不会找到那些服务器变量,因为它没有在服务器中运行。如果您有任何其他方法可以为两者创建单独的日志,请建议我。我应该在单个项目中保留两个 logback.xml 文件吗?或者在一个文件中我可以配置它?
    • 你不能在 /scr/test/resources 中创建一个额外的 logback.xml 供你的测试使用吗?然后你可以在 /src/test/resources/logback.xml 中为日志文件提供不同的路径
    • 现在写入默认情况下它从类路径中获取 logback.xml 那么我应该在我的项目中在哪里配置 logback.xml 的路径?我的意思是在 applicationContext.xml 或 web.xml 或任何其他?应用程序如何知道在运行测试用例时将读取哪个 logback.xml 文件以及在运行应用程序时读取哪个文件?
    • 好的,看来您实际上需要将其重命名为 logback-test.xml。见logback.qos.ch/manual/configuration.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 2019-09-30
    • 2019-04-18
    • 2014-04-07
    相关资源
    最近更新 更多