如何为创建新对象的void方法编写junit测试用例 [英] How to write a junit testcase for a void method that creates a new object

查看:207
本文介绍了如何为创建新对象的void方法编写junit测试用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class SupportController{

    public void disableUserAccount(String username) throws Exception {
        UserAccount userAccount = 
                new UserAccount(Constants.SYSTEM, Constants.CONTAINER, username);
        UserAccount.disableAccount();
    }
}

我如何测试创建的useraccount是否被禁用?

How would i test that the useraccount created is disabled?

推荐答案

有三种基本解决方案:


  1. 使用可以模拟的工厂类

  2. 使用可以模拟调用构造函数

  3. 更新类以使用可在测试环境中重写的默认作用域或受保护作用域工厂方法。

PowerMock 并不总能与其他参赛者一起比赛(例如SpringJUnit4TestRunner)。我通常会因为这个原因而避免使用它,并且它会修改已编译的代码。

PowerMock does not always play well with other runners (for example SpringJUnit4TestRunner). I usually avoid it for this reason and the fact that it modifies the compiled code.

可覆盖的工厂方法是另一种选择。为此,您必须扩展类并覆盖工厂方法。这意味着测试是针对被测试类的实例运行的,该实例实际上不是被测试的类,而是可测试的子类。这对我来说有味道,所以我倾向于尽可能避免它。

The overridable factory method is another option. To do this you must extend the class and override the factory method. This means that the test is running against an instance of the class under test that is not actually the class under test but a testable subclass. This has test-smell to me so I tend to avoid it where possible.

工厂类方法是我首选的解决方案。传入默认的Factory类创建 UserAccount 。在你的测试中提供了一个模拟的(我使用 Mockito )版本的工厂。

The factory class method is my preferred solution. Pass in a Factory class that be default creates the UserAccount. In your test provide a mocked (I use Mockito) version of the factory.

这篇关于如何为创建新对象的void方法编写junit测试用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆