大麻是一种能够使用的方法。
- generate instance of Class X (a class variable passed in arg) and
- override some of it s method
更具体地说,第X类我想要凌驾于括号内。
- Contains no default constructor (e.g. all constructors with args)
- Constructors calling non-private method within the same class
Originally I thought it s quite simple to use reflection or something similar, Then I found there s limitation on implementing my requirement.
- For refection: Can only override "interface" via java.lang.reflect.Proxy http://download.oracle.com/javase/1.3/docs/guide/reflection/proxy.html
- for cglib: it cannot create instance of no default constructor and constructor calling non-private member methods http://insufficientinformation.blogspot.com/2007/12/spring-dynamic-proxies-vs-cglib-proxies.html
I think this is achievable, since Mockito can do all kinds of method injection runtime.
Please anyone give some advise, Thanks.
The pseudo-code I image is like this:
createAndOverride(Class X) {
X newObj = X.newInstance(args) {
@override
methodOfX(args2) {
...
}
}
return newObj;
}
- Original problem scenario
I was intended to test a Class which has several methods calling X1.get(), X2.get(), X3.get()
In some test case, I need to make Xn.get() to return something I can control for test (e.g. null)
Due to below constraint:
- But due to mock tool restriction to JMock 1.0 (I have no control :( ), so I cannot just simply mock Xn.get() to returns "someSpecifiedObjects"
- Xn has no null constructors and constructors calling non-private member
My workaround is self made Xn Class and pass them to test case to let Cn.get() to be expected
code example:
ClassToTest.SomeMethod(new X1() {
@override
get() {
return someSpecifiedObjects;
}
});
And this kind of thing is spread-ed over the Test Case.
Therefore, In order to reduce duplicate code, I would like to build a method to generate Xn instance with specified overrided method for test. e.g.
X1 x1 = createAndOverride(X1);
然后,该职位的问题就出现了。