1

有一个项目对我来说是周转的,现在我的任务是为控制器做一个单元测试。我试图从网上搜索一些教程,这是控制器的一种方法,这是我发现的:

1. http://developer.teradata.com/viewpoint/reference/viewpoint-pdk-cookbook/how-to -create-unit-tests-for-controllers
2. http://www.java-tutorial.ch/software-testing/easymock-tutorial

上面的链接没有填满玻璃。我是新手Unit Testing,下面是控制器

控制器的一个方法:

 private boolean insertNewUser( String name, String username, String password, String email, String userType,
                                   String team, String[] projectid,HttpSession session )
    {
        UsersDAO usersDAO = new UsersDAO();
        ArrayList<Integer> projects = new ArrayList<Integer>();
        boolean insert;

        String sessionType = ( String ) session.getAttribute( SessionUtility.SESSION_TYPE );
        if( sessionType.equalsIgnoreCase( SessionUtility.TYPE_SUPERADMIN ) )
        {
            if( userType.equalsIgnoreCase( SessionUtility.TYPE_ADMIN ) ||
                userType.equalsIgnoreCase( SessionUtility.TYPE_SUPERADMIN ) )
            {
                if( projectid != null )
                {
                    for( int i = 0; i < projectid.length; i++ )
                    {
                        projects.add( Integer.parseInt( projectid[i] ) );
                    }
                }
            }
            }
        if( !projects.contains( Integer.parseInt( ( String ) session.getAttribute( SessionUtility.SESSION_PROJECT ) ) ) )
        {
            projects.add( Integer.parseInt( ( String ) session.getAttribute( SessionUtility.SESSION_PROJECT ) ) );
        }
        insert = usersDAO.insertNewUser( name, username, password, email, userType, team, projects );

        return insert;

    }

问题:如何为控制器进行单元测试?示例方法如上。

如果您需要更多说明,请发表评论。

更新: Easymock 的例子会很棒

4

2 回答 2

0

您可以使用grails.test.ControllerUnitTestCase并创建如下内容:

class ControllerTests extends grails.test.ControllerUnitTestCase {
void testInsert() {
    controller.params.query = "Insert Query";
    controller.insert();
    assertEquals ("expected result", controller.response.contentAsString);
}

}

于 2013-07-22T07:17:25.243 回答
0

您利用 Spring 的单元测试并创建类似这样的东西(http://static.springsource.org/spring-batch/reference/html/testing.html):

import static org.junit.Assert.*;

    @Before
    private void setUp(){
        //init variables here
    }

    @Test
    private boolean insertNewUser(){
//initialize this variables:

 String name, String username, String password, String email, String userType,
  String team, String[] projectid,HttpSession session ;

        String sessionType = ( String ) session.getAttribute( SessionUtility.SESSION_TYPE );
        assertEquals(sessionType, SessionUtility.TYPE_SUPERADMIN);
        assertEquals(userType, SessionUtility.TYPE_ADMIN);
        assertEquals(userType, SessionUtility.TYPE_SUPERADMIN);
        assertNotNull(projectId);

    }
于 2013-07-22T07:23:16.003 回答