简体   繁体   English

实例化jUnit测试类

[英]Instantiate jUnit test Class

I have a jUnit class extending a class whose protected methods I need to test. 我有一个jUnit类,该类扩展了我需要测试其受保护方法的类。

@RunWith(...)
@Configuration(...)
public class testA extends A{
    @Test
    public void testProtectedMethod1(){
    .. 
    }
}

Now, the class A needs a certain variable (a DAO) to be set while instantiation. 现在,类A需要在实例化时设置某个变量(DAO)。 Running this code throws IllegalArgumentException - DAO must be provided. 运行此代码将引发IllegalArgumentException-必须提供DAO。

Things I have tried : 我尝试过的事情:

1) Manually setting the DAO using @Before - didn't work 1)使用@Before手动设置DAO-不起作用

2) Specifying a bean for the test class with DAO's property set - didn't work. 2)为具有DAO的属性集的测试类指定Bean-不起作用。

How can I instantiate this jUnit class with an inherited property? 如何使用继承的属性实例化此jUnit类?

Your class under test should probably not be one you are inheriting from in your Unit test class. 被测类可能不应该是您在单元测试类中继承的类。 Also, testing private methods is inherently difficult (if not impossible) because of the way that JUnit (and indeed Java) are designed. 而且,由于JUnit(甚至Java)的设计方式,测试私有方法本质上是困难的(如果不是不可能的话)。

The whole point of using a unit tests and TDD is to be able to test the public methods of your class under test. 使用单元测试和TDD的全部目的是能够测试被测类的公共方法。 If you are trying to test a private method, you probably want to rethink your (functional) class design in the first place. 如果您尝试测试私有方法,则可能首先要重新考虑您的(功能)类设计。 Is it following the Single Responsibility Principle ? 是否遵循单一责任原则

If you wish to make an exception to the general rule that we only test public methods, perhaps make your private method protected or package access (and make sure your test class has the same package name as your class under test). 如果您希望对仅测试公共方法的一般规则作例外处理,则可以使您的私有方法受到保护或对程序包进行访问(并确保您的测试类与被测类具有相同的程序包名称)。

Either way, it is bad practice in JUnit to have your test class inherit from your class under test and you should avoid that. 无论哪种方式,让您的测试类都从被测类继承都是JUnit的不良做法,您应该避免这种情况。

It turns out that I cannot inject any property of a jUnit test class because its object is instantiated by jUnit runtime itself. 事实证明,我无法注入jUnit测试类的任何属性,因为其对象是由jUnit运行时本身实例化的。 Anyway, I ended up using reflection to test the private methods. 无论如何,我最终使用反射来测试私有方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM