1、选中需要进行测试的service类,右键->new->other->JUnit Test Case,如下图:

  maven多模块下使用JUnit进行单元测试

2、编写测试代码如下:

  AppServiceTest.java

import static org.junit.Assert.assertEquals;
import java.io.IOException;
import javax.servlet.ServletException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import com.lenovo.moc.portal.service.AppService;

/**
 * @author Administrator
 *
 */
@RunWith(JUnit4ClassRunner.class) 
// 由于本测试类位于src/test/java下,而app-context.xml处于src/main/java下,所以需要使用file来获取,
// 否则使用@ContextConfiguration(locations={"classpath:WEB-INF/app-context.xml"})来获取
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/app-context.xml"})   
public class AppServiceTest{

    private MockHttpServletRequest request;  
    private MockHttpServletResponse response; 
    
    @Autowired
    private AppService appService;
    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {
        request = new MockHttpServletRequest();      
        request.setCharacterEncoding("UTF-8");      
        response = new MockHttpServletResponse();              
    }

    /**
     * @throws java.lang.Exception
     */
    @After
    public void tearDown() throws Exception {
    }

    /**
     * Test method for {@link AppService#login(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}.
     */
    @Test
    public void testAdminAppLogin() {
        
        try {
            request.setParameter("key", "value");
            appService.login(request, response);
            assertEquals(response.getStatus(), 200);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
View Code

相关文章:

  • 2021-05-07
  • 2021-06-25
  • 2022-02-11
  • 2021-09-30
  • 2021-08-29
  • 2021-04-05
  • 2022-01-13
  • 2022-12-23
猜你喜欢
  • 2021-07-23
  • 2021-12-08
  • 2021-11-18
  • 2021-10-18
  • 2022-01-01
  • 2022-01-09
相关资源
相似解决方案