How to write a junit testcase for a void method that creates a new object

大憨熊 提交于 2019-12-02 09:09:24

I would suggest using Mock Objects.

Besides that, you can check the JUnit FAQ, where you can find a section about testing methods that return void.

Often if a method doesn't return a value, it will have some side effect. Actually, if it doesn't return a value AND doesn't have a side effect, it isn't doing anything.

There may be a way to verify that the side effect actually occurred as expected

There are three basic solutions:

  1. Use a factory class that can be mocked
  2. Use PowerMock which can mock calls to constructors
  3. Update the class to use a default scope or protected scope factory method which could be overridden in a test env.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!