究竟该如何测试? (单元测试,JUnit,PhpUnit)

时间:2014-07-30 08:21:27

标签: java php unit-testing testing junit

这个问题可能过于局部化了。 让我们假设我有论坛系统来测试。让我们删除用户和他的帖子。为简化起见,让我使用伪代码:

class User
{
    function add() { ... }

    function delete (userID)
    {
        container::getOrCreateUserPostObject.deletePostsByUserID (userID)
        DELETE FROM users WHERE ID = userID
    }
}

class UserPost
{
    function deletePostsByUserID (userID)
    {
        DELETE FROM posts WHERE USERID = userID
    }
}

现在必须进行测试:

function testDeleteUser()
{
    container::getOrCreateUserObject.add();
    container::getOrCreateUserObject.add();
    container::getOrCreateUserObject.delete (1)
    // now check in the DB that how many records left, really one was deleted etc.
}

另一个测试

function testDeletePosts
{
    container::getOrCreateUserPostObject.deletePostsByUserID (1);
    // again, now check in the DB that how many records left, really one was deleted etc.
}
到目前为止,这看起来还不错。用户删除和用户帖子删除工作,他们的测试独立。 是的,独立的。我们检查是否可以删除用户并检查是否可以删除他的帖子。我们没有检查我们是否删除了帖子的用户!有两个很好的工作“乐高”元素,但如果我们将它们放在一起就可以了吗? 如果我将此“全局”测试发送到testDeleteUser(),那么我会重复删除后测试代码...

1 个答案:

答案 0 :(得分:1)

我不知道我是否帮助你,但是在测试中,你不应该真的依赖于特定的用户ID,就像你在testDeletePosts()中做的那样,你应该在这里添加一个用户此外,添加一些帖子,并再次删除这些帖子。所以你的测试是完全独立的。

更新

用于检查参照完整性的类似内容

function testDeleteUsersAndPosts
{
    addedUsers[0] = user.add();
    addedPosts[0] = post.add(addedUsers[0], 'first Post')
    addedPosts[1] = post.add(addedUsers[0], 'second Post')

    addedUsers[1] = user.add();
    addedPosts[2] = post.add(addedUsers[1], 'third Post for the second user')

    // Check how many posts you have
    allPosts = post.get().count()

    for (id in addedUsers)
    {
         user.delete(id)
    }


    // Check how many posts you have now
    allPostsNow = post.get().count();

    return allPostsNow == (allPosts -3)
}

此类内容仅用于检查“仅删除帖子”

function testDeletePosts
{
    userID = user.add();
    addedPost = post.add(userID, 'first Post')

    // Check how many posts you have
    allPosts = post.get().count()

    post.delete(addedPost)

    return post.get(addedPost) == false
}