Compare commits

..

84 Commits

Author SHA1 Message Date
金戟
30570ae69d fix: verifier should compare arrays in deep 2023-05-17 19:08:42 +08:00
金戟
320ee632b7 test: add cases of collection tool methods 2022-12-17 08:12:54 +08:00
金戟
ba284f6518 doc: introduce CollectionTool class 2022-12-16 23:09:19 +08:00
金戟
c6e861e5cf refactor: move fastListOf method out of CollectionTool 2022-12-15 09:42:02 +08:00
金戟
0287d27d85 release v0.7.9 2022-12-14 19:25:55 +08:00
金戟
1e9079e8d3 feat: move collection creation methods to CollectionTool 2022-12-14 00:34:03 +08:00
金戟
e7a2b06698 feat: generate none-null object for classes not in jvm package 2022-12-13 23:30:47 +08:00
金戟
ab87ef1fd0 feat: cache constructor parameter types for efficiency 2022-12-12 08:20:58 +08:00
金戟
d5c1f780de feat: invoke super constructor explicitly in generated class 2022-12-11 20:06:46 +08:00
金戟
a463bcbfd9 fix: correctly handle array type 2022-12-11 12:03:37 +08:00
金戟
c53f1e01f0 feat: find best constructor of super class 2022-12-11 08:10:46 +08:00
金戟
12989aa612 refactor: merge UNREACHABLE_CLASSES and PRELOADED_CLASSES 2022-12-10 12:22:37 +08:00
金戟
61a3090431 refactor: update junit version 2022-12-09 22:09:12 +08:00
金戟
e9ce61d83c doc: fix test case name 2022-12-06 11:59:57 +08:00
金戟
d9f65189f7 feat: add RICH_INTERFACE option to avoid introduce omni class in system interface implementation 2022-12-04 17:52:19 +08:00
金戟
1446382f53 feat: handle many special cases of system class creation 2022-12-04 07:34:42 +08:00
金戟
ada70f88c0 feat: get generic type mapping recursively 2022-12-03 17:15:18 +08:00
金戟
65b58d0861 feat: avoid duplicate method declaration 2022-12-02 23:17:13 +08:00
金戟
a67dd7b73f feat: add targetClassName parameter to mock invoke annotation 2022-12-01 23:41:41 +08:00
金戟
1f6fc2e4bc feat: support generate system interface class 2022-12-01 00:32:21 +08:00
金戟
eb8ccb0a40 feat: choose correct constructor for system preloaded classes 2022-11-30 00:02:42 +08:00
金戟
dcbb305e10 fix: incorrect onmi constructor option judgement 2022-11-27 21:13:05 +08:00
金戟
8c0a74264a refactor: move string util methods to core package 2022-11-27 21:10:53 +08:00
金戟
dcc5108149 fix: look for outer mock class failed 2022-11-26 22:05:24 +08:00
金戟
0a40e07739 feat: upgrade transmittable-thread-local to 2.14.2 2022-11-26 22:04:53 +08:00
金戟
9e5f722076 fix: duplicate naming 2022-11-25 23:05:49 +08:00
金戟
1dcbe6b0f2 feat: get rid of Pair class 2022-11-25 15:00:04 +08:00
金戟
e4ff8ce57e fix: typo and condition in comment 2022-11-24 22:13:06 +08:00
金戟
47871d0eb6 feat: always consider class with MockContainer annotation as mock class 2022-11-23 14:05:10 +08:00
金戟
e52538acf3 feat: parse mock class considering MockContainer annotation 2022-11-21 00:41:27 +08:00
金戟
db91a0ea34 feat: transform mock class according to MockContainer annotation 2022-11-20 20:11:46 +08:00
金戟
d912e53ebc feat: implement EXCEPT_INTERFACE option of omni constructor 2022-11-20 13:09:04 +08:00
金戟
1e2e1e6d84 doc: update test case name 2022-11-20 00:05:52 +08:00
金戟
1bb6007eb5 test: also verify mock invocation times 2022-11-20 00:01:24 +08:00
金戟
6632fae529 feat: add testcase for inherited mock container 2022-11-19 23:32:06 +08:00
金戟
9018301bfc feat: add MockContainer annotation 2022-11-19 22:28:28 +08:00
金戟
dbaeb3bcf1 doc: should do both push and push tag 2022-11-17 21:05:15 +08:00
金戟
fc7e4af2c6 feat: support generate class with inherited genericity 2022-11-14 20:36:44 +08:00
金戟
76cff45123 feat: support generate class with dollar in name 2022-11-14 20:36:37 +08:00
金戟
5c8ef00fce feat: support generate parameterized class 2022-11-14 20:36:29 +08:00
金戟
f8501b0722 fix: generate correct type name 2022-11-14 22:40:34 +08:00
金戟
46e4499035 release v0.7.8 2022-11-13 20:13:40 +08:00
金戟
f508f7aba9 refactor: always use the collection method in core module 2022-11-13 18:15:42 +08:00
金戟
6e029f61d8 feat: add util method for quick create set 2022-11-01 16:35:47 +08:00
金戟
b654a3cfaa feat: support generate method with template types 2022-10-09 20:31:13 +08:00
金戟
038ae8dba0 feat: support construct simple interface and abstract class 2022-10-08 20:20:18 +08:00
金戟
11a5565cee feat: use same package path of parent to avoid access error 2022-10-08 11:30:43 +08:00
金戟
ba77a0138c fix: let the kotlin testcases pass with 'mvn test' locally 2022-09-29 17:22:35 +08:00
金戟
9788dd9ecc feat: add common used collection creation function to library 2022-08-09 14:25:52 +08:00
金戟
55a6e141fc doc: update faq to fit current mock inovke annotation parameter 2022-06-11 22:48:26 +08:00
金戟
81a2817b6c fix: fit for jvm 1.6 2022-06-04 23:23:59 +08:00
金戟
ef6099a63d feat: generate empty sub class for interface 2022-06-04 23:11:12 +08:00
金戟
3c11676408 feat: add original InMemoryJavaCompiler 2022-06-03 13:29:25 +08:00
金戟
b2a87bffbe refactor: use constant dollar symbol 2022-05-29 14:08:35 +08:00
金戟
1a2083416e doc: describe the MockContext fields 2022-05-29 11:35:23 +08:00
金戟
c1e6d00953 doc: one more thing to mention 2022-05-28 17:39:35 +08:00
金戟
39b742b290 release v0.7.7 2022-05-28 13:34:27 +08:00
金戟
0a5666c0be fix: only generate named lambda method for mocked ones 2022-05-28 13:26:37 +08:00
金戟
006e742c28 fix: upgrade asm to support java 17 2022-05-19 19:00:59 +08:00
金戟
237b9ebb15 doc: fix link to invoke matcher page 2022-05-19 18:53:13 +08:00
金戟
7aedcf63b5 release v0.7.6 2022-04-22 17:14:33 +08:00
金戟
0f64d52718 feat: should skip mockito generated class 2022-04-22 17:09:56 +08:00
金戟
4ed1323a62 feat: package mapping map shuold be ordered 2022-04-22 16:38:26 +08:00
Fan Lin
ae1ba8b4ff Merge pull request #274 from zcbbpo/ISSUES-272
Fixed java9+ String makeConcatWithConstants not work for method refer…
2022-04-01 17:01:30 +08:00
zcbbpo
00f25d3622 Fixed java9+ String makeConcatWithConstants not work for method reference 2022-04-01 11:14:49 +08:00
金戟
2e58ae8360 release v0.7.5 2022-03-08 12:38:35 +08:00
金戟
ff54c57608 fix: should handle array type method properly 2022-03-08 12:35:18 +08:00
金戟
351b3399e6 feat: elastic plugin class should contain only one constructor 2022-02-20 22:22:00 +08:00
金戟
df9e2395cc doc: describe no unique public constructor error 2022-02-20 22:09:45 +08:00
金戟
b9064d3d47 doc: intellij plugin usage english edition 2022-02-05 22:52:48 +08:00
金戟
c967456569 doc: add intellij plugin usage 2022-02-05 21:28:28 +08:00
金戟
692b4435aa release v0.7.4 2022-02-02 21:02:28 +08:00
金戟
6379f16266 fix #261, java.net.URL is loaded before OmniClassHandler 2022-02-02 21:02:28 +08:00
Fan Lin
63a6a9fdca Merge pull request #259 from oldratlee/upgrade-ttl
upgrade TTL to 2.12.4, fix ClassCircularityError
2022-01-12 10:05:23 +08:00
Jerry Lee
7e24503611 upgrade TTL to 2.12.4, fix ClassCircularityError
more discussion see
https://github.com/alibaba/transmittable-thread-local/issues/278
2022-01-12 00:43:02 +08:00
金戟
3120eba3af update release note 2022-01-10 20:55:39 +08:00
金戟
02f15177fc release v0.7.3 2022-01-09 22:45:14 +08:00
Fan Lin
a25f14c0ec Merge pull request #257 from zcbbpo/FIXED-INVOKEINTERFACE_1
Fixed invokeinterface issuse
2022-01-07 14:55:25 +08:00
jimcao
635cbf62fb completed 2022-01-06 15:13:32 +08:00
jimcao
17b31b39dd refine code 2022-01-06 13:13:09 +08:00
jimcao
0d43d93a29 temp update 2022-01-06 11:52:18 +08:00
jimcao
66db3cff7d temp 2022-01-05 09:49:49 +08:00
jimcao
3343a26de8 Add interface static test case 2022-01-05 09:12:38 +08:00
jimcao
de2e520d95 Fixed interface default method 2022-01-04 18:02:49 +08:00
107 changed files with 3295 additions and 671 deletions

View File

@@ -31,7 +31,9 @@
|-- tool ➜ 项目开发过程中的工具脚本
|-- demo
| |-- java-demo ➜ Java语言的示例代码
| `-- kotlin-demo ➜ Kotlin语言的示例代码
| |-- kotlin-demo ➜ Kotlin语言的示例代码
| |-- android-demo ➜ Android项目的示例代码
| `-- spock-demo ➜ Spock测试框架的示例代码
`-- docs ➜ 项目使用文档
```

View File

@@ -9,11 +9,7 @@ Usage Document: https://alibaba.github.io/testable-mock/#/en-us/
## Roadmap
`TestableMock` is still under heavy development, the following version plans may be adjusted during the iteration
- `v0.6` it's the current version, refer to the [issue](https://github.com/alibaba/testable-mock/issues) list for the work in progress
- `v0.7` better anti-refactoring support of mocking, allow quick mock all method in specified class
- `v1.0` all functions are stable, a brand-new start
`TestableMock` is still under heavy development, if you get sucked somehow, just go ahead raise an [issue](https://github.com/alibaba/testable-mock/issues) for it.
## Directory Structure
@@ -27,7 +23,9 @@ Usage Document: https://alibaba.github.io/testable-mock/#/en-us/
|-- tool ➜ Scripts for project maintain
|-- demo
| |-- java-demo ➜ Java code example
| `-- kotlin-demo ➜ Kotlin code example
| |-- kotlin-demo ➜ Kotlin code example
| |-- android-demo ➜ Android app code example
| `-- spock-demo ➜ Spock framwork code example
`-- docs ➜ Source code of usage document
```

View File

@@ -49,7 +49,7 @@ dependencies {
testImplementation 'androidx.test:runner:1.4.0-alpha05'
testImplementation 'junit:junit:4.+'
testImplementation 'org.robolectric:robolectric:4.5.1'
testImplementation 'com.alibaba.testable:testable-all:0.7.2'
testImplementation 'com.alibaba.testable:testable-all:0.7.9'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

View File

@@ -13,8 +13,8 @@ repositories {
dependencies {
testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
testImplementation('com.alibaba.testable:testable-all:0.7.2')
testAnnotationProcessor('com.alibaba.testable:testable-processor:0.7.2')
testImplementation('com.alibaba.testable:testable-all:0.7.9')
testAnnotationProcessor('com.alibaba.testable:testable-processor:0.7.9')
}
tasks.withType(JavaCompile) {

View File

@@ -11,8 +11,8 @@
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>5.6.2</junit.version>
<testable.version>0.7.2</testable.version>
<junit.version>5.9.1</junit.version>
<testable.version>0.7.9</testable.version>
</properties>
<dependencies>
@@ -35,7 +35,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<version>3.0.0-M7</version>
<configuration>
<argLine>@{argLine} -javaagent:${settings.localRepository}/com/alibaba/testable/testable-agent/${testable.version}/testable-agent-${testable.version}.jar</argLine>
</configuration>
@@ -56,7 +56,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.6</version>
<version>0.8.8</version>
<executions>
<execution>
<id>prepare-agent</id>

View File

@@ -8,7 +8,7 @@ import com.alibaba.demo.basic.model.mock.Color;
* 演示父类变量引用子类对象时的Mock场景
* Demonstrate scenario of mocking method from sub-type object referred by parent-type variable
*/
public class DemoInherit {
public class DemoReference {
/**
* call method overridden by subclass via parent class variable

View File

@@ -1,9 +0,0 @@
package com.alibaba.demo.basic.issue;
public abstract class AbstractServiceA {
public String put(Object input) {
return "object";
}
}

View File

@@ -1,9 +0,0 @@
package com.alibaba.demo.basic.issue;
public class ServiceA extends AbstractServiceA {
public String get(Object input) {
return super.put(input);
}
}

View File

@@ -15,6 +15,14 @@ public class Child {
private InnerChild subChild;
/**
* 这是一个私有内部类
* An private inner class
*/
private class InnerChild {
private String secret;
}
/* ---------------------------------------
以下Getters/Setters方法仅为便于功能演示而添加
并非OmniConstructor或OmniAccessor功能所需
@@ -36,12 +44,4 @@ public class Child {
this.subChild = subChild;
}
/**
* 这是一个私有内部类
* An private inner class
*/
private class InnerChild {
private String secret;
}
}

View File

@@ -0,0 +1,25 @@
package com.alibaba.demo.inherit;
/**
* 演示使用@MockContainer注解实现Mock容器类的多重继承
* Demonstrate multiple inherit of mock container class with @MockContainer annotation
*/
public class DemoMultipleInherit {
private String prefix() {
return "ori_";
}
private String middle() {
return "gin";
}
private String suffix(int some, String more, Object[] parameters) {
return "_al";
}
public String entry() {
return prefix() + middle() + suffix(0, null, null);
}
}

View File

@@ -0,0 +1,21 @@
package com.alibaba.demo.inherit;
/**
* 演示使用extends关键字实现Mock容器类的继承
* Demonstrate inherit of mock container class
*/
public class DemoSingleInherit {
private String prefix() {
return "re_";
}
private String suffix() {
return "_al";
}
public String entry(String word) {
return prefix() + word + suffix();
}
}

View File

@@ -0,0 +1,42 @@
package com.alibaba.demo.lambda;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* @author jim
*/
public interface BaseDemo {
default void blackHole(Object... ignore) {}
default void consumesRun(Runnable r) {
r.run();
}
default void consumesFunction0(Runnable f) {
f.run();
}
default <T> void consumesFunction1(Consumer<T> f) {
f.accept(null);
}
default <T, R> void consumesFunction2(Function<T, R> f) {
f.apply(null);
}
default <T1, T2, R> void consumesFunction3(BiFunction<T1, T2, R> f) {
f.apply(null, null);
}
default <T> void consumesSupplier(Supplier<T> supplier) {
supplier.get();
}
default <T, R> void consumesTwoFunction2(Function<T, R> f1, Function<T, R> f2) {
f1.apply(null);
f2.apply(null);
}
}

View File

@@ -0,0 +1,121 @@
package com.alibaba.demo.lambda;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author jim
*/
@SuppressWarnings("SimplifyStreamApiCallChains")
public class CollectionListCodeDemo implements BaseDemo {
public void list() {
List<User> userList = getUsers();
double d = userList.stream()
.map(v -> v)
.map(v -> Function.<User>identity().apply(v))
.map(User::getId)
.mapToDouble(Double::valueOf)
.reduce(0, Double::sum);
//.reduce(0, (v1, v2) -> v1 + v2);
blackHole(d);
blackHole(userList.stream()
.map(User::getId)
.mapToLong(Long::valueOf)
.reduce(0, Long::sum));
blackHole(userList.stream()
.map(User::getId)
.mapToInt(Long::intValue)
.reduce(0, Integer::sum));
Map<Long, User> map = userList.stream()
.filter(User::isActive)
.collect(Collectors.toMap(User::getId, Function.identity(), (v1, v2) -> v1));
blackHole(map);
List<User> l1 = userList.stream()
.collect(Collectors.toList())
.stream()
.collect(Collectors.toSet())
.stream()
.collect(Collectors.groupingBy(User::getName))
.entrySet()
.stream()
.filter(v -> v.getValue().stream().anyMatch(User::isActive))
.map(Map.Entry::getValue)
.flatMap(Collection::parallelStream)
.collect(Collectors.groupingBy(User::getId))
.values()
.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
blackHole(l1);
userList.stream()
.map(User::isActive)
.reduce(Boolean::logicalAnd)
.ifPresent(this::blackHole);
}
private List<User> getUsers() {
List<User> userList = new ArrayList<>();
for (int i=0; i<10; i++) {
userList.add(getUser(i));
}
return userList;
}
private User getUser(int index) {
User u1 = new User();
u1.id = (long)index;
u1.name = "u" + index;
u1.age = index;
u1.active = true;
return u1;
}
private static class User {
private Long id;
private String name;
private int age;
private boolean active;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
}

View File

@@ -0,0 +1,86 @@
package com.alibaba.demo.lambda;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* @author jim
*/
public class InvokeInterfaceDemo implements BaseDemo {
public void collectionInterfaceDefaultOrStatic() {
blackHole(collectionStreamTest());
blackHole(arraysStreamTest());
}
public void interfaceDefault() {
ILambda l = new LambdaFoo();
consumesRun(l::run);
consumesFunction1(l::function1);
}
public void interfaceStatic() {
consumesRun(ILambda::staticRun);
consumesFunction1(ILambda::staticFunction1);
}
public Object collectionStreamTest() {
List<List<String>> testList = new ArrayList<>();
List<String> fooList = new ArrayList<>();
fooList.add("123");
fooList.add("456");
testList.add(fooList);
return testList.stream()
//.flatMap(v -> v.stream())
.flatMap(Collection::stream)
.map(Double::valueOf)
.map(BigDecimal::new)
.reduce(BigDecimal::add);
}
public Object arraysStreamTest() {
List<String[]> zz = new ArrayList<>();
zz.add(new String[]{"1", "2", "3"});
return zz.stream()
.flatMap(Arrays::stream)
.map(Double::valueOf)
.map(BigDecimal::new)
.reduce(BigDecimal::add);
}
public void objectStaticMethodReference() {
List<Boolean> f = new ArrayList<>();
f.add(false);
f.add(false);
f.add(false);
blackHole(f.stream()
.reduce(Boolean::logicalAnd)
.get()
);
}
public interface ILambda {
default void run() {
}
default void function1(String s) {
}
static void staticRun() {
}
static void staticFunction1(String s) {
}
}
public static class LambdaFoo implements ILambda {
}
}

View File

@@ -9,7 +9,7 @@ import java.util.function.Supplier;
* @author jimca
*/
@SuppressWarnings({"WrapperTypeMayBePrimitive", "ResultOfMethodCallIgnored", "MismatchedReadAndWriteOfArray", "unused"})
public class ExternalLambdaDemo {
public class InvokeVirtualDemo {
public void string1() {
String s = "";
@@ -197,8 +197,8 @@ public class ExternalLambdaDemo {
}
public void function3() {
ExternalLambdaDemo externalLambdaDemo = new ExternalLambdaDemo();
consumesFunction3(externalLambdaDemo::f3);
InvokeVirtualDemo invokeVirtualDemo = new InvokeVirtualDemo();
consumesFunction3(invokeVirtualDemo::f3);
}
public Boolean f3(String s1, Long l) {

View File

@@ -1,79 +1,33 @@
package com.alibaba.demo.lambda;
import java.util.Collections;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author jim
*/
public class StaticInstanceReference {
public class StaticInstanceReference implements BaseDemo {
private static A a = new A();
private static final StaticClassA STATIC_CLASS_A = new StaticClassA();
public void staticMethodReference() {
//consumesRun(() -> a.doIt());
//A b = new A();
//consumesRun(b::doIt);
consumesRun(a::doIt);
consumesFunction1(a::function1);
consumesFunction2(a::function2);
consumesFunction3(a::function3);
consumesRun(STATIC_CLASS_A::doIt);
consumesFunction1(STATIC_CLASS_A::function1);
consumesFunction2(STATIC_CLASS_A::function2);
consumesFunction3(STATIC_CLASS_A::function3);
}
private void consumesRun(Runnable r) {
r.run();
}
private <T> void consumesFunction1(Consumer<T> r) {
r.accept(null);
}
private <T, R> void consumesFunction2(Function<T, R> r) {
r.apply(null);
}
private <T1, T2, R> void consumesFunction3(BiFunction<T1, T2, R> r) {
r.apply(null, null);
}
public static class A {
public static class StaticClassA {
public void doIt() {
}
public void function1(String s) {
}
public Integer function2(String s) {
public Integer function2(String s) {
return 1;
}
}
public Integer function3(String s, Double d) {
return 1;
}
}
public static class XBean {
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
public void foo() {
List<XBean> testList = Collections.emptyList();
//noinspection RedundantOperationOnEmptyContainer
List<Long> response = testList.stream().map(XBean::getId).distinct().collect(Collectors.toList());
public Integer function3(String s, Double d) {
return 1;
}
}
}

View File

@@ -13,11 +13,17 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
* 演示父类变量引用子类对象时的Mock场景
* Demonstrate scenario of mocking method from sub-type object referred by parent-type variable
*/
class DemoInheritTest {
class DemoReferenceTest {
private DemoInherit demoInherit = new DemoInherit();
private DemoReference demoReference = new DemoReference();
public static class Mock {
/**
* 当需要引用原对象时不加`targetClass`参数将原类型作为Mock方法的首个参数建议将参数命名为`self`
* When method body need to refer the invoked object, skip the use `targetClass` parameter,
* and add a parameter `self` with target class type before other paramter of the target method
*/
@MockInvoke(targetMethod = "put")
private void put_into_box(Box self, String something) {
self.put("put_" + something + "_into_box");
@@ -28,77 +34,81 @@ class DemoInheritTest {
self.put("put_" + something + "_into_blackbox");
}
@MockInvoke(targetMethod = "get")
private String get_from_box(Box self) {
/**
* 当不需要引用原对象时将目标类型作为`@MockInvoke`注解的`targetClass`参数值即可
* When the invoked object is not used in the mock method, set `targetClass` value to the type who owns the mocked method
*/
@MockInvoke(targetClass = Box.class, targetMethod = "get")
private String get_from_box() {
return "get_from_box";
}
@MockInvoke(targetMethod = "get")
private String get_from_blackbox(BlackBox self) {
@MockInvoke(targetClass = BlackBox.class, targetMethod = "get")
private String get_from_blackbox() {
return "get_from_blackbox";
}
@MockInvoke(targetMethod = "getColor")
private String get_color_from_color(Color self) {
@MockInvoke(targetClass = Color.class, targetMethod = "getColor")
private String get_color_from_color() {
return "color_from_color";
}
@MockInvoke(targetMethod = "getColor")
private String get_color_from_blackbox(BlackBox self) {
@MockInvoke(targetClass = BlackBox.class, targetMethod = "getColor")
private String get_color_from_blackbox() {
return "color_from_blackbox";
}
@MockInvoke(targetMethod = "getColorIndex")
private String get_colorIdx_from_color(Color self) {
@MockInvoke(targetClass = Color.class, targetMethod = "getColorIndex")
private String get_colorIdx_from_color() {
return "colorIdx_from_color";
}
}
@Test
void should_mock_call_sub_object_method_by_parent_object() {
BlackBox box = (BlackBox)demoInherit.putIntoBox();
BlackBox box = (BlackBox) demoReference.putIntoBox();
verifyInvoked("put_into_box").withTimes(1);
assertEquals("put_data_into_box", box.get());
}
@Test
void should_mock_call_sub_object_method_by_sub_object() {
BlackBox box = demoInherit.putIntoBlackBox();
BlackBox box = demoReference.putIntoBlackBox();
verifyInvoked("put_into_blackbox").withTimes(1);
assertEquals("put_data_into_blackbox", box.get());
}
@Test
void should_mock_call_parent_object_method_by_parent_object() {
String content = demoInherit.getFromBox();
String content = demoReference.getFromBox();
verifyInvoked("get_from_box").withTimes(1);
assertEquals("get_from_box", content);
}
@Test
void should_mock_call_parent_object_method_by_sub_object() {
String content = demoInherit.getFromBlackBox();
String content = demoReference.getFromBlackBox();
verifyInvoked("get_from_blackbox").withTimes(1);
assertEquals("get_from_blackbox", content);
}
@Test
void should_mock_call_interface_method_by_interface_object() {
String color = demoInherit.getColorViaColor();
String color = demoReference.getColorViaColor();
verifyInvoked("get_color_from_color").withTimes(1);
assertEquals("color_from_color", color);
}
@Test
void should_mock_call_interface_method_by_sub_class_object() {
String color = demoInherit.getColorViaBox();
String color = demoReference.getColorViaBox();
verifyInvoked("get_color_from_blackbox").withTimes(1);
assertEquals("color_from_blackbox", color);
}
@Test
void should_mock_call_interface_method_by_sub_interface_object() {
String colorIdx = demoInherit.getColorIdxViaColor();
String colorIdx = demoReference.getColorIdxViaColor();
verifyInvoked("get_colorIdx_from_color").withTimes(1);
assertEquals("colorIdx_from_color", colorIdx);
}

View File

@@ -1,23 +0,0 @@
package com.alibaba.demo.basic.issue;
import com.alibaba.testable.core.annotation.MockInvoke;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ServiceATest {
private ServiceA sa = new ServiceA();
public static class Mock {
@MockInvoke(targetClass = AbstractServiceA.class, targetMethod = "put")
public String put(Object input) {
return "mocked";
}
}
@Test
void get() {
assertEquals("mocked", sa.get(123));
}
}

View File

@@ -0,0 +1,48 @@
package com.alibaba.demo.inherit;
import com.alibaba.testable.core.annotation.MockContainer;
import com.alibaba.testable.core.annotation.MockInvoke;
import org.junit.jupiter.api.Test;
import static com.alibaba.testable.core.matcher.InvocationVerifier.verifyInvoked;
import static org.junit.jupiter.api.Assertions.*;
/**
* 演示使用@MockContainer注解实现Mock容器类的多重继承
* Demonstrate multiple inherit of mock container class with @MockContainer annotation
*/
class DemoMultipleInheritTest {
private DemoMultipleInherit demoMultipleInherit = new DemoMultipleInherit();
public static class PrefixMock {
@MockInvoke(targetClass = DemoMultipleInherit.class)
private String prefix() {
return "in_";
}
}
public static class SuffixMock {
@MockInvoke(targetClass = DemoMultipleInherit.class)
private String suffix(int some, String more, Object[] parameters) {
return "_it";
}
}
@MockContainer(inherits = { PrefixMock.class, SuffixMock.class })
public static class Mock {
@MockInvoke(targetClass = DemoMultipleInherit.class)
private String middle() {
return "her";
}
}
@Test
public void should_use_mock_method_in_parent_class() {
assertEquals("in_her_it", demoMultipleInherit.entry());
verifyInvoked("prefix").withTimes(1);
verifyInvoked("middle").withTimes(1);
verifyInvoked("suffix").withTimes(1);
}
}

View File

@@ -0,0 +1,38 @@
package com.alibaba.demo.inherit;
import com.alibaba.testable.core.annotation.MockInvoke;
import org.junit.jupiter.api.Test;
import static com.alibaba.testable.core.matcher.InvocationVerifier.verifyInvoked;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* 演示Mock容器类的继承
* Demonstrate inherit of mock container class with extends keyword
*/
class DemoSingleInheritTest {
private DemoSingleInherit demoSingleInherit = new DemoSingleInherit();
public static class BasicMock {
@MockInvoke(targetClass = DemoSingleInherit.class)
private String suffix() {
return "_ck";
}
}
public static class Mock extends BasicMock {
@MockInvoke(targetClass = DemoSingleInherit.class)
private String prefix() {
return "mo_";
}
}
@Test
public void should_use_mock_method_in_parent_class() {
assertEquals("mo_test_ck", demoSingleInherit.entry("test"));
verifyInvoked("prefix").withTimes(1);
verifyInvoked("suffix").withTimes(1);
}
}

View File

@@ -0,0 +1,25 @@
package com.alibaba.demo.lambda;
import com.alibaba.testable.core.annotation.MockInvoke;
import org.junit.jupiter.api.Test;
/**
* @author jim
*/
public class CollectionListCodeDemoTest {
private final CollectionListCodeDemo instance = new CollectionListCodeDemo();
public static class Mock {
@MockInvoke(targetClass = String.class, targetMethod = "contains")
public boolean mockContains(CharSequence s) {
return false;
}
}
@Test
public void listTest() {
instance.list();
}
}

View File

@@ -0,0 +1,69 @@
package com.alibaba.demo.lambda;
import com.alibaba.testable.core.annotation.MockInvoke;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;
import static com.alibaba.testable.core.matcher.InvocationVerifier.verifyInvoked;
/**
* @author jim
*/
public class InvokeInterfaceDemoTest {
private final InvokeInterfaceDemo instance = new InvokeInterfaceDemo();
public static class Mock {
@MockInvoke(targetClass = InvokeInterfaceDemo.ILambda.class, targetMethod = "run")
private void mockILambdaRun() {
}
@MockInvoke(targetClass = InvokeInterfaceDemo.ILambda.class, targetMethod = "function1")
private void mockILambdaFunction1(String s) {
}
@SuppressWarnings("unchecked")
@MockInvoke(targetClass = Collection.class, targetMethod = "stream")
<E> Stream<E> mockStream() {
List<E> fooList = new ArrayList<>();
fooList.add((E) "123");
fooList.add((E) "456");
return fooList.stream();
}
@MockInvoke(targetClass = Boolean.class, targetMethod = "logicalAnd")
public static boolean mockLogicalAnd(boolean a, boolean b) {
return false;
}
}
@Test
public void shouldMockCollectionStream() {
instance.collectionInterfaceDefaultOrStatic();
verifyInvoked("mockStream").withTimes(1);
}
@Test
public void shouldMockInterfaceDefault() {
instance.interfaceDefault();
verifyInvoked("mockILambdaRun").withTimes(1);
verifyInvoked("mockILambdaFunction1").withTimes(1);
}
@Test
public void shouldMockObjectStaticMethodReference() {
instance.objectStaticMethodReference();
verifyInvoked("mockLogicalAnd").withTimes(2);
}
@Test
public void shouldMockInterfaceStatic() {
instance.interfaceStatic();
}
}

View File

@@ -8,8 +8,8 @@ import static com.alibaba.testable.core.matcher.InvocationVerifier.verifyInvoked
/**
* @author zcbbpo
*/
public class ExternalLambdaDemoTest {
private final ExternalLambdaDemo lambdaDemo = new ExternalLambdaDemo();
public class InvokeVirtualDemoTest {
private final InvokeVirtualDemo lambdaDemo = new InvokeVirtualDemo();
@SuppressWarnings("unused")
public static class Mock {
@@ -34,7 +34,7 @@ public class ExternalLambdaDemoTest {
return "";
}
@MockInvoke(targetClass = ExternalLambdaDemo.class, targetMethod = "f3")
@MockInvoke(targetClass = InvokeVirtualDemo.class, targetMethod = "f3")
public Boolean mockF3(String s1, Long l) {
return true;
}

View File

@@ -1,8 +1,6 @@
package com.alibaba.demo.lambda;
import com.alibaba.testable.core.annotation.MockDiagnose;
import com.alibaba.testable.core.annotation.MockInvoke;
import com.alibaba.testable.core.model.LogLevel;
import org.junit.jupiter.api.Test;
import static com.alibaba.testable.core.matcher.InvocationVerifier.verifyInvoked;
@@ -13,18 +11,23 @@ import static com.alibaba.testable.core.matcher.InvocationVerifier.verifyInvoked
*/
public class StaticInstanceReferenceTest {
private StaticInstanceReference instance = new StaticInstanceReference();
private final StaticInstanceReference instance = new StaticInstanceReference();
//@MockDiagnose(LogLevel.VERBOSE)
public static class Mock {
@MockInvoke(targetClass = StaticInstanceReference.A.class, targetMethod = "doIt")
@MockInvoke(targetClass = StaticInstanceReference.StaticClassA.class, targetMethod = "doIt")
private void mockDoIt() {
}
@MockInvoke(targetClass = StaticInstanceReference.StaticClassA.class)
private Integer function2(String s) {
return 2;
}
}
@Test
public void shouldMockT1() {
public void shouldMockDoIt() {
instance.staticMethodReference();
verifyInvoked("mockDoIt").withTimes(1);
verifyInvoked("function2").withTimes(1);
}
}

View File

@@ -17,8 +17,8 @@ dependencies {
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
testImplementation("org.junit.jupiter:junit-jupiter:5.6.2")
testImplementation("com.alibaba.testable:testable-all:0.7.2")
testAnnotationProcessor("com.alibaba.testable:testable-processor:0.7.2")
testImplementation("com.alibaba.testable:testable-all:0.7.9")
testAnnotationProcessor("com.alibaba.testable:testable-processor:0.7.9")
}
tasks.withType<KotlinCompile> {

View File

@@ -13,8 +13,8 @@
<kotlin.version>1.3.72</kotlin.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>5.6.2</junit.version>
<testable.version>0.7.2</testable.version>
<junit.version>5.9.1</junit.version>
<testable.version>0.7.9</testable.version>
</properties>
<dependencies>
@@ -50,7 +50,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<version>3.0.0-M7</version>
<!-- <configuration>-->
<!-- <argLine>@{argLine} -javaagent:${settings.localRepository}/com/alibaba/testable/testable-agent/${testable.version}/testable-agent-${testable.version}.jar</argLine>-->
<!-- </configuration>-->
@@ -71,7 +71,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.6</version>
<version>0.8.8</version>
<executions>
<execution>
<id>prepare-agent</id>

View File

@@ -8,7 +8,7 @@ import com.alibaba.demo.basic.model.mock.Color
* 演示父类变量引用子类对象时的Mock场景
* Demonstrate scenario of mocking method from sub-type object referred by parent-type variable
*/
class DemoInherit {
class DemoReference {
/**
* call method overridden by subclass via parent class variable

View File

@@ -109,7 +109,7 @@ internal class DemoMockTest {
}
@Test
fun should_get_test_case_name() {
fun should_set_mock_context() {
MOCK_CONTEXT["case"] = "special_case"
// synchronous
assertEquals("mock_special", demoMock.callerOne())

View File

@@ -12,9 +12,9 @@ import org.junit.jupiter.api.Test
* 演示父类变量引用子类对象时的Mock场景
* Demonstrate scenario of mocking method from sub-type object referred by parent-type variable
*/
internal class DemoInheritTest {
internal class DemoReferenceTest {
private val demoInherit = DemoInherit()
private val demoReference = DemoReference()
class Mock {
@MockInvoke(targetMethod = "put")
@@ -50,42 +50,42 @@ internal class DemoInheritTest {
@Test
fun should_mock_call_sub_object_method_by_parent_object() {
val box = demoInherit.putIntoBox() as BlackBox
val box = demoReference.putIntoBox() as BlackBox
InvocationVerifier.verifyInvoked("put_into_box").withTimes(1)
assertEquals("put_data_into_box", box.get())
}
@Test
fun should_mock_call_sub_object_method_by_sub_object() {
val box = demoInherit.putIntoBlackBox()
val box = demoReference.putIntoBlackBox()
InvocationVerifier.verifyInvoked("put_into_blackbox").withTimes(1)
assertEquals("put_data_into_blackbox", box.get())
}
@Test
fun should_mock_call_parent_object_method_by_parent_object() {
val content = demoInherit.fromBox
val content = demoReference.fromBox
InvocationVerifier.verifyInvoked("get_from_box").withTimes(1)
assertEquals("get_from_box", content)
}
@Test
fun should_mock_call_parent_object_method_by_sub_object() {
val content = demoInherit.fromBlackBox
val content = demoReference.fromBlackBox
InvocationVerifier.verifyInvoked("get_from_blackbox").withTimes(1)
assertEquals("get_from_blackbox", content)
}
@Test
fun should_mock_call_interface_method_by_interface_object() {
val color = demoInherit.colorViaColor
val color = demoReference.colorViaColor
InvocationVerifier.verifyInvoked("get_color_from_color").withTimes(1)
assertEquals("color_from_color", color)
}
@Test
fun should_mock_call_interface_method_by_sub_class_object() {
val color = demoInherit.colorViaBox
val color = demoReference.colorViaBox
InvocationVerifier.verifyInvoked("get_color_from_blackbox").withTimes(1)
assertEquals("color_from_blackbox", color)
}

View File

@@ -14,8 +14,8 @@ repositories {
dependencies {
testImplementation 'org.codehaus.groovy:groovy-all:3.0.7'
testImplementation 'org.spockframework:spock-core:2.0-M5-groovy-3.0'
testImplementation('com.alibaba.testable:testable-all:0.7.2')
testAnnotationProcessor('com.alibaba.testable:testable-processor:0.7.2')
testImplementation('com.alibaba.testable:testable-all:0.7.9')
testAnnotationProcessor('com.alibaba.testable:testable-processor:0.7.9')
}
tasks.withType(JavaCompile) {

View File

@@ -12,7 +12,7 @@
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<testable.version>0.7.2</testable.version>
<testable.version>0.7.9</testable.version>
</properties>
<dependencyManagement>
@@ -70,7 +70,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<version>3.0.0-M7</version>
<configuration>
<argLine>-javaagent:${settings.localRepository}/com/alibaba/testable/testable-agent/${testable.version}/testable-agent-${testable.version}.jar</argLine>
<useFile>false</useFile>

View File

@@ -0,0 +1,131 @@
Collection Tools
---
During test data preparation, various collection types are often used. However, collection data initialization in Java needs series of redundant call to the `add()` or `put()` method, making the code very tedious.
Inspired by the collection operations of Kotlin language, `TestableMock` draws on a set of concise collection construction method, which makes the creation of Java collection objects elegant.
The utility class `CollectionTool` provides following global static methods:
## arrayOf
Quickly construct an array of any type, equivalent to Kotlin's `arrayOf()` method.
Usage example:
```java
import static com.alibaba.testable.core.tool.CollectionTool.arrayOf;
// Construct a string array
String[] manyWords = arrayOf("this", "is", "an", "example");
// Construct a double array
Double[] manyValues = arrayOf(1.0D, 2.0D, 3.0D);
```
## listOf
Quickly construct an list of any type, equivalent to Kotlin's `mutableListOf()` method.
Usage example:
```java
import static com.alibaba.testable.core.tool.CollectionTool.listOf;
// Construct a string list
List<String> manyWords = listOf("this", "is", "an", "example");
// Construct a double list
List<Double> manyValues = listOf(1.0D, 2.0D, 3.0D);
```
## setOf
Quickly construct an set of any type, equivalent to Kotlin's `mutableSetOf()` method.
Usage example:
```java
import static com.alibaba.testable.core.tool.CollectionTool.setOf;
// Construct a string set
Set<String> manyWords = setOf("this", "is", "an", "example");
// Construct a double set
Set<Double> manyValues = setOf(1.0D, 2.0D, 3.0D);
```
## mapOf
Quickly construct an map of any type, equivalent to Kotlin's `mutableMapOf()` method.
Usage example:
```java
import static com.alibaba.testable.core.tool.CollectionTool.mapOf;
import static com.alibaba.testable.core.tool.CollectionTool.entryOf;
// Construct a string to string map
Map<String, String> manyWords = mapOf(
entryOf("language", "java"),
entryOf("type", "unittest"),
entryOf("library", "testable")
);
// Construct a integer to double map
Map<Integer, Double> manyValues = mapOf(
entryOf(1, 10.12D),
entryOf(2, 20.24D),
entryOf(3, 30.36D)
);
```
## orderedMapOf
Quickly construct ordered map (LinkedListMap) of any type. Compared with the HashMap map created by `mapOf()`, when traversing its keys or values in a loop, the order will always be the same as entries passed to `orderedMapOf()` method during construction.
Usage example:
```java
import static com.alibaba.testable.core.tool.CollectionTool.orderedMapOf;
import static com.alibaba.testable.core.tool.CollectionTool.entryOf;
// Construct a string to string ordered map
Map<String, String> manyWords = orderedMapOf(
entryOf("language", "java"),
entryOf("type", "unittest"),
entryOf("library", "testable")
);
// Construct a integer to double ordered map
Map<Integer, Double> manyValues = orderedMapOf(
entryOf(1, 10.12D),
entryOf(2, 20.24D),
entryOf(3, 30.36D)
);
```
## entryOf
Used with `mapOf()` and `orderedMapOf()` methods to construct a map.
## slice
Used to extract a part of data from any type of array to a new array.
Usage example:
```java
import static com.alibaba.testable.core.tool.CollectionTool.slice;
import static com.alibaba.testable.core.tool.CollectionTool.arrayOf;
// Extract the elements of the specified string array from subscript 1 to 3
// the returned new array content are ["is", "a", "simple"]
String[] fullWords = arrayOf("this", "is", "a", "simple", "example");
String[] partOfWords = slice(fullWords, 1, 3);
// If only given the index of starting position, all elements after this position are extracted
// the new array returned in the following example is [5, 8, 13, 21]
Integer[] fibonacci = arrayOf(1, 1, 2, 3, 5, 8, 13, 21);
Integer[] partOfFibonacci = slice(fibonacci, 4);
```

View File

@@ -25,9 +25,9 @@ In the code, there are often cases of using <u>interface variables or parent cla
At this time, follow a principle that the type of the first parameter of the mock method is always the same as the type of the variable that initiated the call.
Therefore, regardless of whether the actually called method comes from the parent class or the subclass, and whether the subclass overrides the method. If the calling variable is of the parent type (or interface type), the first parameter type of the mock method should use the corresponding parent type (or interface) type.
Therefore, regardless of whether the actually called method comes from the parent class or the subclass, and whether the subclass overrides the method. If the calling variable is of the parent type (or interface type), the `targetClass` value of `@MockInvoke` annotation (or the first parameter type of the mock method) should use the corresponding parent type / interface type.
See the use case of the `DemoInheritTest` test class in the Java and Kotlin examples.
See the use case of the `DemoReferenceTest` test class in the Java and Kotlin examples.
#### 5. How to mock generic methods (template methods)?
@@ -62,3 +62,9 @@ This framework will run Android unit tests on a standard JVM virtual machine, wh
This problem is caused by the system `Class Path` content is too long, and has nothing to do with `TestableMock`. However, it should be noted that IntelliJ provides two auxiliary solutions: `JAR manifest` and `classpath file`. If `TestableMock` is used in the test, please select `JAR manifest`.
![jar-manifest.png](https://img.alicdn.com/imgextra/i2/O1CN01hfC5YE1Kw0gBIlB2x_!!6000000001227-2-tps-752-171.png)
#### 10. Getting "no unique public constructor for [xxx]" error with `OmniConstructor`?
When the `omni.constructor.enhance.enable` configuration is enabled, `TestableMock` will dynamically add a constructor with a parameter of `java.lang.Void` when each class is loaded into memory to avoid the original type constructor exceptions that may be thrown. The above error occurs when some frameworks do not allow multiple constructors for some classes.
The solution is to add the package path where the error class is located to the `omni.constructor.enhance.pkgPrefix.excludes` configuration, which tell `TestableMock` not to dynamically add constructors to these classes. For details, please refer to the [Global Run Arguments](en-us/doc/javaagent-args.md) document.

View File

@@ -35,9 +35,9 @@ Parent parent = OmniConstructor.newInstance(Parent.class);
parent.getChild().getGrandChild().getContent();
```
> **Note 1**: In the current version, the member fields of type interface or abstract class will still be initialized to `null`, this problem will be fixed in the future.
>
> **Note 2**: Based on the light-weight principle, in the default mode, `OmniConstructor` will only uses the original constructor of the class to create objects. For POJO and most model layer objects, this mode has been able to meet the needs.
> Interface and abstract class can also be instantiated by `OmniConstructor`, you can try it e.g. `OmniConstructor.newInstance(CharSequence.class)` ^_^
> **Notice**: Based on the light-weight principle, in the default mode, `OmniConstructor` will only uses the original constructor of the class to create objects. For POJO and most model layer objects, this mode has been able to meet the needs.
> But for more complex situations, such as when certain class have constructors throwing exceptions or contain other statements that hinder the normal execution of the construction, the object construction may fail.
> In those situations, you can use the [Testable global configuration](en-us/doc/javaagent-args.md) `omni.constructor.enhance.enable = true` to enable bytecode enhancement mode of `OmniConstructor`, in this mode, any Java class can be constructed.

View File

@@ -1,5 +1,35 @@
# Release Note
## 0.7.9
- fix many issues relate to interface instance creation of `OmniConstructor`
- add `@MockContainer` annotation to support multiply parents inheritance between mock classes
- add `targetClassName` parameter to `@MockInvoke` annotation, support mock method of private internal class
- move collection creation methods from `CollectionUtil` class to `CollectionTool` class
## 0.7.8
- support use `OmniConstructor` class to create instance of interface type or abstract class
- provide a `CollectionUtil` class which contains many utility collection creation methods
- fix a compatibility issue with jdk 1.6
## 0.7.7
- skip bytecode process for classes which not associated to any mock class, speed up test initialization
- only generate substitution method for mocked method references
- fix compatibility issues with jdk 17
## 0.7.6
- define package mapping rule according to order in config, to avoid a short path overwrite longer ones
- fix compatibility issue with jdk 9+
- skip classes generated by mockito during `OmniConstructor` bytecode enhancing
## 0.7.5
- fix an issue cause mocking method with array return type fails
## 0.7.4
- fix an `OmniConstructor.newInstance()` fail issue caused by `java.net.URL` class cannot be instrumented
## 0.7.3
- fix an issue cause mock failed with referring to method defined in interface
## 0.7.2
- fix an issue cause mock failed with static method reference

View File

@@ -7,6 +7,7 @@ Use TestableMock
- [Access private members of the class under test](en-us/doc/private-accessor.md): enable unit tests directly invoke or access private members of the class under test, solve the problems of private member initialization and private method testing
- [Quickly construct complicated parameter object](en-us/doc/omni-constructor.md)generate arbitrarily nested object instances, simplify their internal member assignment methods, solve the problem of long initialization codes for method parameters
- [Assist test void method](en-us/doc/test-void-method.md): use the mock validator to check the internal logic of method, solve the problem that unit testing is difficult to implement to the method with no return value
- [Quickly create collection instances](en-us/doc/collection-tools.md): provide utility methods for collection creation, solve the problem of redundant codes during java test data preparation
## Use in Maven project
@@ -16,7 +17,7 @@ It is recommended to add a `property` field that identifies the TestableMock ver
```xml
<properties>
<testable.version>0.7.2</testable.version>
<testable.version>0.7.9</testable.version>
</properties>
```
@@ -63,8 +64,8 @@ Add dependence of `TestableMock` in `build.gradle` file:
```groovy
dependencies {
testImplementation('com.alibaba.testable:testable-all:0.7.2')
testAnnotationProcessor('com.alibaba.testable:testable-processor:0.7.2')
testImplementation('com.alibaba.testable:testable-all:0.7.9')
testAnnotationProcessor('com.alibaba.testable:testable-processor:0.7.9')
}
```

View File

@@ -0,0 +1,46 @@
Use IntelliJ Plugin
---
There are some typical operations in the process of using`TestableMock` library, such as define a mock class, copy signature of the method invoked and convert it to mock method definition. While the mock result does not match expectation, we have to debug the mock affection via [Self-Help Troubleshooting](zh-cn/doc/troubleshooting.md) guide during runtime. With the help of IDE plugin, part of the patterned operations can be automatically completed to further optimize the experience of `TestableMock`.
Currently `TestableMock` provided only [IntelliJ IDEA](https://www.jetbrains.com/idea/) plugin. (According to the [2020](https://www.jrebel.com/blog/2020-java-technology-report#IDE) and [2021](https://www.jrebel.com/blog/2021-java-technology-report) Java Technology Trends Report released by JRebel, IntelliJ IDEA has become the IDE of choice with the highest percentage of Java developers)
## Usage
Open preference dialog, search "Testable-Mock" in plugin market, reach `Testable-Mock Helper` plugin and click "install", then restart IDE.
![install](https://img.alicdn.com/imgextra/i2/O1CN013twjqN2803NVtvJEP_!!6000000007869-0-tps-2342-566.jpg)
#### 1. **Generate Mock Class**
After plugin installed, right click in any java class, choose "Generate Testable TestClass"
![mock-class](https://img.alicdn.com/imgextra/i1/O1CN01gNsunh21jfVufv6EU_!!6000000007021-0-tps-546-291.jpg)
A test class containing a mock container class will be automatically generated in the same package path location as the current class in the `test` directory of the project (named after `CurrentClass + Test`)
#### 2. **Create Mock Method**
Select any method invocation, right click and choose "Copy Testable Mock-Method" or "Copy Mock-Method To TestClass"
![mock-method](https://img.alicdn.com/imgextra/i4/O1CN01K38Zsh1NrNYLlrUZ9_!!6000000001623-0-tps-642-264.jpg)
The former will convert the method signature of selected invocation into a mock method definition and store it on the clipboard; the latter will directly insert the converted mock method into the corresponding mock class.
## Build from source code
Beside install plugin from market, you can also build it from source.
Make sure you have jdk 11 installed, execute below command:
```bash
git clone https://github.com/zcbbpo/testable-idea
cd testable-idea
./gradlew clean build
```
After build, the packaged zip file is lay in `build/distributions/` folder, you can install it by "Install Plugin From Disk" menu.
![from-local](https://img.alicdn.com/imgextra/i3/O1CN01YMHefk26MNS4pH4ZI_!!6000000007647-0-tps-2342-516.jpg)
Finally, special thanks to the contribution of `TestableMock` IntelliJ IDEA plugin made by @[zcbbpo](https://github.com/zcbbpo).

View File

@@ -159,13 +159,13 @@ private Data mockDemo() {
}
```
For complete code examples, see the `should_get_source_method_name()` and `should_get_test_case_name()` test cases in the `java-demo` and `kotlin-demo` sample projects.
For complete code examples, see the `should_get_source_method_name()` and `should_set_mock_context()` test cases in the `java-demo` and `kotlin-demo` sample projects.
### 3. Verify the sequence and parameters of the mock method being invoked
In test cases, you can use the `InvocationVerifier.verifyInvoked()` method, and cooperate with `with()`, `withInOrder()`, `without()`, `withTimes()` and other methods to verify the mock call situation.
For details, please refer to the [Check Mock Call](en-us/doc/matcher.md) document.
For details, please refer to the [Check Mock Call](en-us/doc/invoke-matcher.md) document.
### 4. Special instructions

View File

@@ -4,6 +4,7 @@
- [Private Accessor](en-us/doc/private-accessor.md)
- [Omni Constructor](en-us/doc/omni-constructor.md)
- [Test Void Method](en-us/doc/test-void-method.md)
- [Collection Tools](en-us/doc/collection-tools.md)
- Usage Guide
- [Verify Mock Invocation](en-us/doc/invoke-matcher.md)
@@ -11,6 +12,7 @@
- [Reusing Mock Methods](en-us/doc/mock-method-reusing.md)
- [Use MockWith Annotation](en-us/doc/use-mock-with.md)
- [Use Package Mapping](en-us/doc/use-package-mapping.md)
- [Use IntelliJ Plugin](en-us/doc/use-intellij-plugin.md)
- [Frequently Asked Questions](en-us/doc/frequently-asked-questions.md)
- [Mock Invocation In Thread Pool](zh-cn/doc/with-thread-pool.md)
- [Use TestableMock In IDE](en-us/doc/use-in-ide.md)

View File

@@ -20,11 +20,14 @@
- 作用于Mock容器类中的方法
| 参数 | 类型 | 是否必须 | 默认值 | 作用 |
| --- | --- | --- | ---- | --- |
| targetClass | Class | 否 | N/A | 指定Mock目标的调用者类型 |
| targetMethod | String | 否 | N/A | 指定Mock目标的方法名 |
| scope | MockScope | 否 | MockScope.GLOBAL | 指定Mock的生效范围 |
| 参数 | 类型 | 是否必须 | 默认值 | 作用 |
| --- | --- | --- | ---- | --- |
| targetClass | Class | 否 | N/A | 指定Mock目标的调用者类型 |
| targetClassName | String | 否 | N/A | `targetClass`相同,主要用于无法直接引用的私有内部类 |
| targetMethod | String | 否 | N/A | 指定Mock目标的方法名 |
| scope | MockScope | 否 | MockScope.GLOBAL | 指定Mock的生效范围 |
> 说明:`targetClass`和`targetClassName`参数不能同时使用
#### @MockNew
@@ -36,6 +39,15 @@
| --- | --- | --- | ---- | --- |
| scope | MockScope | 否 | MockScope.GLOBAL | 指定Mock的生效范围 |
#### @MockContainer
标识指定类为Mock容器类并从任意个其他Mock类里继承所有Mock方法。
- 作用于Mock容器类
| 参数 | 类型 | 是否必须 | 默认值 | 作用 |
| ---- | --- | --- | --- | --- |
| inherits | Class[] | 否 | N/A | 指定要继承的Mock类 |
#### @MockWith

View File

@@ -0,0 +1,129 @@
常用集合构建工具
---
在编写测试数据的时候经常会用到各种集合类型的对象然而Java原生的集合类型需要反复调用`add()``put()`方法来添加数据,使代码显得十分冗长。
`TestableMock`借鉴了Kotlin语言简洁的集合构造方法提供了一个实用的集合构造工具类`CollectionTool`让Java集合对象的创建从此变得优雅。
这个工具类提供了以下全局静态方法:
## arrayOf
快速构造任意类型的数组等效于Kotlin的`arrayOf()`方法。
用法示例:
```java
import static com.alibaba.testable.core.tool.CollectionTool.arrayOf;
// 构造一个字符串数组
String[] manyWords = arrayOf("this", "is", "an", "example");
// 构造一个浮点值数组
Double[] manyValues = arrayOf(1.0D, 2.0D, 3.0D);
```
## listOf
快速构造任意类型的列表等效于Kotlin的`mutableListOf()`方法。
用法示例:
```java
import static com.alibaba.testable.core.tool.CollectionTool.listOf;
// 构造一个字符串列表
List<String> manyWords = listOf("this", "is", "an", "example");
// 构造一个浮点值列表
List<Double> manyValues = listOf(1.0D, 2.0D, 3.0D);
```
## setOf
快速构造任意类型的集合等效于Kotlin的`mutableSetOf()`方法。
用法示例:
```java
import static com.alibaba.testable.core.tool.CollectionTool.setOf;
// 构造一个字符串集合
Set<String> manyWords = setOf("this", "is", "an", "example");
// 构造一个浮点值集合
Set<Double> manyValues = setOf(1.0D, 2.0D, 3.0D);
```
## mapOf
快速构造任意类型的无序映射表等效于Kotlin的`mutableMapOf()`方法。
用法示例:
```java
import static com.alibaba.testable.core.tool.CollectionTool.mapOf;
import static com.alibaba.testable.core.tool.CollectionTool.entryOf;
// 构造一个字符串到字符串的映射
Map<String, String> manyWords = mapOf(
entryOf("language", "java"),
entryOf("type", "unittest"),
entryOf("library", "testable")
);
// 构造一个整型数值到浮点数值的映射
Map<Integer, Double> manyValues = mapOf(
entryOf(1, 10.12D),
entryOf(2, 20.24D),
entryOf(3, 30.36D)
);
```
## orderedMapOf
快速构造任意类型的有序映射表LinkedListMap相较于`mapOf()`创建的HashMap对象当在循环中遍历它的键或值列表时其访问顺序始终会与构造时传给`orderedMapOf()`方法的数据顺序一致。
用法示例:
```java
import static com.alibaba.testable.core.tool.CollectionTool.orderedMapOf;
import static com.alibaba.testable.core.tool.CollectionTool.entryOf;
// 构造一个字符串到字符串的有序映射
Map<String, String> manyWords = orderedMapOf(
entryOf("language", "java"),
entryOf("type", "unittest"),
entryOf("library", "testable")
);
// 构造一个整型数值到浮点数值的有序映射
Map<Integer, Double> manyValues = orderedMapOf(
entryOf(1, 10.12D),
entryOf(2, 20.24D),
entryOf(3, 30.36D)
);
```
## entryOf
配合`mapOf()``orderedMapOf()`方法使用,用于构造映射表。
## slice
用于提取任意类型数组中间的一部分数据,组成新的数组。
用法示例:
```java
import static com.alibaba.testable.core.tool.CollectionTool.slice;
import static com.alibaba.testable.core.tool.CollectionTool.arrayOf;
// 提取指定字符串数组从下标1到3之间的元素得到的新数组内容为["is", "a", "simple"]
String[] fullWords = arrayOf("this", "is", "a", "simple", "example");
String[] partOfWords = slice(fullWords, 1, 3);
// 只传入起始位置下标,提取该位置之后的所有元素,下例返回的新数组内容为[5, 8, 13, 21]
Integer[] fibonacci = arrayOf(1, 1, 2, 3, 5, 8, 13, 21);
Integer[] partOfFibonacci = slice(fibonacci, 4);
```

View File

@@ -9,7 +9,7 @@
| Spock | 动态代理 | 类 | 不能Mock私有/静态和构造方法 | 较复杂 | 一般 |
| PowerMock | 自定义类加载器 | 类 | **任何方法皆可** | 较复杂 | **较好** |
| JMockit | 运行时字节码修改 | 类 | 不能Mock构造方法(new操作符) | 较复杂 | 一般 |
| TestableMock | 运行时字节码修改 | 方法 | **任何方法皆可** | **容易** | 一般 |
| TestableMock | 运行时字节码修改 | 方法 | **任何方法皆可** | **容易** | **较好** |
`Mockito`是Java最老牌的Mock工具稳定性和易用性较好IntelliJ和Eclipse都有专用插件支持。相对不足之处在于Mock功能稍弱在必要情况下需与其他Mock工具配合使用。
@@ -19,8 +19,12 @@
`JMockit`是一款功能性与易用性均居于`Mockito``PowerMock`之间的Mock工具较好的弥补了两者各自的不足。该项目在2017年尝试推出JMockit2重写版本但未能完成目前处于不活跃的维护状态。
相比之下,`TestabledMock`的功能与`PowerMock`基本平齐,且极易上手,只需掌握`@MockInvoke`注解就可以完成绝大多数任务
相比之下,`TestabledMock`的功能与`PowerMock`基本平齐,且极易上手,只需掌握一个`@MockInvoke`注解就可以完成绝大多数Mock操作
当前`TestableMock`的主要不足在于编写Mock方法时IDE无法即时提示方法参数是否正确匹配。若发现匹配效果不符合预期需要通过[自助问题排查](zh-cn/doc/troubleshooting.md)文档提供的方法在运行期进行校验。这个功能理论上能够通过扩展主流IDE插件来补充但目前暂无相关开发计划参见[Issue-104](https://github.com/alibaba/testable-mock/issues/104)。
## TestableMock的不足
此外,由于`TestableMock`独辟蹊径的采用“每个业务类拥有一个专属Mock容器类”的思维方式将Mock方法定义与单元测试用例解耦一方面使得Mock方法具有默认可复用性单元测试用例也因此变得更干净纯粹另一方面也导致Mock方法定义变得零散生命周期管理起来相对困难对现有开发者的Mock编写习惯会带来一定改变。
为了便于开发者进行Mock工具的合理选型我们认为客观的强调`TestabledMock`存在的不足,与阐述它的优点同样重要。
任何事物都有两面性。由于`TestableMock`独辟蹊径采用“每个业务类拥有一个专属Mock容器类”的思维方式将Mock方法定义与单元测试用例解耦一方面使得Mock方法具有默认可复用性单元测试用例也因此变得更干净纯粹另一方面也导致Mock方法定义变得零散生命周期管理起来相对困难对现有开发者的Mock编写习惯会带来一定改变。
此外,`TestableMock`最初的设计主要面向标准单元测试场景(每个类有自己的测试用例,测试类与被测类基本逐一对应)。为了最大限度的提升易用性,把需要用到的注解、操作步骤都减少到最少,`TestableMock`采用了许多“约定优于配置”的设计。譬如被测量、测试类与Mock容器类在同一包路径且分别按约定命名等。对于单元测试较规范的项目而言`TestableMock`将极大降低Mock引入的成本对于规范不足的项目依然可以结合`@MockWith`、包路径映射等功能完成相同的Mock效果但应当尤其注意这些“花哨”的功能对代码可读性和可维护性带来的负面影响。

View File

@@ -29,9 +29,9 @@
这时候遵循一个原则Mock方法的首个参数类型**始终与发起调用的变量类型一致**。
因此不论实际被调用方法来自父类还是子类也不论子类是否覆写该方法。若发起调用的变量为父类型或接口类型则Mock方法的首个参数类型都应该使用相应的父类(或接口)类型。
因此,不论实际被调用方法来自父类还是子类,也不论子类是否覆写该方法。若发起调用的变量为父类型(或接口类型),则`@MockInvoke`注解的`targetClass`参数值(或Mock方法的首个参数类型都应该使用相应的父类/接口类的类型。
参见Java和Kotlin示例中`DemoInheritTest`测试类的用例。
参见Java和Kotlin示例中`DemoReferenceTest`测试类的用例。
#### 5. 如何Mock对于泛型方法(模板方法)
@@ -64,3 +64,9 @@ Kotlin语言中的`String`类型实际上是`kotlin.String`,而非`java.lang.S
这个问题是由于系统ClassPath包含太多路径所致与是否使用`TestableMock`无关。但需要注意的是IntelliJ提供了两种辅助解决机制`JAR manifest``classpath file`,若测试中使用了`TestableMock`,请选择`JAR manifest`
![jar-manifest.png](https://img.alicdn.com/imgextra/i2/O1CN01hfC5YE1Kw0gBIlB2x_!!6000000001227-2-tps-752-171.png)
#### 10. 使用`OmniConstructor`遇到"no unique public constructor for [xxx]"错误?
当启用`omni.constructor.enhance.enable`配置时,`TestableMock`会在每个类加载进内存时动态添加一个参数为`java.lang.Void`的构造方法,用于避开原类型构造方法里可能抛出的异常。若遇到某些框架不允许类型存在多个构造方法的时候,就会出现上述错误。
解决办法是将报错类所在的包路径添加到`omni.constructor.enhance.pkgPrefix.excludes`配置中,告知`TestableMock`不要对这些类动态添加构造方法即可。配置方法详见[全局运行参数](zh-cn/doc/javaagent-args.md)文档。

View File

@@ -35,9 +35,9 @@ Parent parent = OmniConstructor.newInstance(Parent.class);
parent.getChild().getGrandChild().getContent();
```
> **注意 1** :在当前版本中,类型为接口或抽象类的成员字段依然会被初始化为`null`,此问题将在后续版本修复
>
> **注意 2** :基于轻量优先原则,默认模式下,`OmniConstructor`仅利用类型原有的构造方法来创建对象对于绝大多数POJO和`Model`层对象而言这种模式已经能够满足需要。
> 接口类型和抽象类型也可以直接通过`OmniConstructor`实例化哦,不信试试看`OmniConstructor.newInstance(CharSequence.class)` ^_^
> **注意**:基于轻量优先原则,默认模式下,`OmniConstructor`仅利用类型原有的构造方法来创建对象对于绝大多数POJO和`Model`层对象而言这种模式已经能够满足需要。
> 但对于更复杂的情形,譬如遇到某些类型的构造方法会抛出异常或包含其他妨碍构造正常执行的语句时,对象构造可能会失败。
> 此时可通过[Testable全局配置](zh-cn/doc/javaagent-args.md)`omni.constructor.enhance.enable = true`启用`OmniConstructor`的字节码增强模式在该模式下任何Java类型皆可构造。

View File

@@ -1,5 +1,35 @@
# Release Note
## 0.7.9
- 修复多处`OmniConstructor`创建接口类型对象相关的问题
- 新增`@MockContainer`注解支持Mock容器类之间的多重继承
- `@MockInvoke`注解新增`targetClassName`参数支持Mock私有内部类的方法
-`CollectionUtil`中的集合构造方法独立为`CollectionTool`工具类并发布
## 0.7.8
- 支持使用`OmniConstructor`工具类自动创建接口和抽象类的实例
- 提供`CollectionUtil`工具类,包含在测试中常用的集合创建方法
- 修复一处JDK 1.6的兼容问题
## 0.7.7
- 未关联Mock类的类型自动跳过字节码处理提升大型项目测试启动速度
- 仅对被Mock的方法引用生成替代方法 (issue-280)
- 修复JDK 17的兼容性问题 (issue-283)
## 0.7.6
- 依据定义顺序匹配包映射规则防止短路径覆盖长路径issue-275
- 修复JDK 9+的兼容性问题issue-270 / pr-274
-`OmniConstructor`字节码增强时忽略Mockito生成的类型issue-197
## 0.7.5
- 修复Mock数组类型返回值方法报错的问题issue-267
## 0.7.4
- 修复`java.net.URL`类无法被instrument导致使用`OmniConstructor`构造报错的问题issue-261
## 0.7.3
- 修复接口方法引用导致Mock报错的问题issue-254
## 0.7.2
- 修复静态方法引用导致Mock报错的问题issue-250

View File

@@ -7,6 +7,7 @@
- [访问被测类私有成员](zh-cn/doc/private-accessor.md):使单元测试能直接调用和访问被测类的私有成员,解决私有成员初始化和私有方法测试的问题
- [快速构造参数对象](zh-cn/doc/omni-constructor.md):生成任意复杂嵌套的对象实例,并简化其内部成员赋值方式,解决被测方法参数初始化代码冗长的问题
- [辅助测试void方法](zh-cn/doc/test-void-method.md)利用Mock校验器对方法的内部逻辑进行检查解决无返回值方法难以实施单元测试的问题
- [快速构造集合对象](zh-cn/doc/collection-tools.md)提供简洁易用的集合构造和常用操作方法解决准备测试数据时Java集合初始化代码冗长的问题
## 在Maven项目中使用
@@ -16,7 +17,7 @@
```xml
<properties>
<testable.version>0.7.2</testable.version>
<testable.version>0.7.9</testable.version>
</properties>
```
@@ -63,8 +64,8 @@
```groovy
dependencies {
testImplementation('com.alibaba.testable:testable-all:0.7.2')
testAnnotationProcessor('com.alibaba.testable:testable-processor:0.7.2')
testImplementation('com.alibaba.testable:testable-all:0.7.9')
testAnnotationProcessor('com.alibaba.testable:testable-processor:0.7.9')
}
```
@@ -110,4 +111,6 @@ test {
> sourceCompatibility = '6' // 或7/8/9/...
> ```
>
> **注意**:由于`Spock`采用基于字符串解析的特殊执行方式,`TestableTool`工具类在`Spock`框架中无法使用。
>
> 完整代码可参考`demo/spock-demo`示例项目。

View File

@@ -0,0 +1,46 @@
使用IntelliJ IDEA插件
---
在使用`TestableMock`工具的过程中经常涉及一些固定操作比如定义Mock容器类、复制需Mock的调用定义并创建Mock方法在执行测试时若发现Mock匹配的效果不符合预期则需要通过[自助问题排查](zh-cn/doc/troubleshooting.md)方法在运行期进行校验。通过IDE插件辅助能够将部分模式化的操作自动完成进一步优化`TestableMock`的使用体验。
目前`TestableMock`提供了 [IntelliJ IDEA](https://www.jetbrains.com/idea/) 的插件支持根据JRebel发布的 [2020](https://www.jrebel.com/blog/2020-java-technology-report#IDE) 和 [2021](https://www.jrebel.com/blog/2021-java-technology-report) Java技术趋势报告IntelliJ IDEA已成为Java开发者使用比例最高的首选IDE
## 使用方法
打开配置项在插件市场中搜索“Testable-Mock”选中`Testable-Mock Helper`插件点击“安装”然后重启IDE。
![install](https://img.alicdn.com/imgextra/i2/O1CN013twjqN2803NVtvJEP_!!6000000007869-0-tps-2342-566.jpg)
#### 1. **创建Mock容器类**
安装完插件后在任意Java类点击右键点击“生成Testable测试类”英文版为“Generate Testable TestClass”
![mock-class](https://img.alicdn.com/imgextra/i1/O1CN01gNsunh21jfVufv6EU_!!6000000007021-0-tps-546-291.jpg)
在项目`test`目录下与当前类相同的包路径位置会自动生成一个包含Mock容器类的测试类`当前类+Test`命名)。
#### 2. **创建Mock方法**
选中任意方法调用点击右键点击“复制方法为Testable-Mock”英文版为“Copy Testable Mock-Method”或“复制Testable-Mock方法到测试类”英文版为“Copy Mock-Method To TestClass”
![mock-method](https://img.alicdn.com/imgextra/i4/O1CN01K38Zsh1NrNYLlrUZ9_!!6000000001623-0-tps-642-264.jpg)
前者会将被选中调用的方法签名并转换为Mock方法定义存放到剪贴板后者则会将转换好的Mock方法直接插入到相应的Mock类里。
## 源码构建
除了通过插件市场安装,也可以直接从源码构建`Testable-Mock Helper`插件。
本地准备JDK 11环境然后执行以下命令
```bash
git clone https://github.com/zcbbpo/testable-idea
cd testable-idea
./gradlew clean build
```
构建完成后,在`build/distributions/`目录下可以找到构建好的插件zip包通过“从本地磁盘安装”菜单加载该插件。
![from-local](https://img.alicdn.com/imgextra/i3/O1CN01YMHefk26MNS4pH4ZI_!!6000000007647-0-tps-2342-516.jpg)
在此,特别感谢 @[zcbbpo](https://github.com/zcbbpo) 对`TestableMock`IntelliJ IDEA插件的贡献。

View File

@@ -159,13 +159,13 @@ private Data mockDemo() {
}
```
完整代码示例见`java-demo``kotlin-demo`示例项目中的`should_get_source_method_name()``should_get_test_case_name()`测试用例。
完整代码示例见`java-demo``kotlin-demo`示例项目中的`should_get_source_method_name()``should_set_mock_context()`测试用例。
### 3. 验证Mock方法被调用的顺序和参数
在测试用例中可用通过`InvocationVerifier.verifyInvoked()`方法,配合`with()``withInOrder()``without()``withTimes()`等方法实现对Mock调用情况的验证。
详见[校验Mock调用](zh-cn/doc/matcher.md)文档。
详见[校验Mock调用](zh-cn/doc/invoke-matcher.md)文档。
### 4. 特别说明

View File

@@ -15,7 +15,7 @@ Mock线程池内的调用
```xml
<properties>
<transmittable.thread.local.version>2.12.1</transmittable.thread.local.version>
<transmittable.thread.local.version>2.14.2</transmittable.thread.local.version>
</properties>
```

View File

@@ -4,6 +4,7 @@
- [直接访问私有成员](zh-cn/doc/private-accessor.md)
- [快速构造复杂入参](zh-cn/doc/omni-constructor.md)
- [测试无返回值的方法](zh-cn/doc/test-void-method.md)
- [常用集合构建工具](zh-cn/doc/collection-tools.md)
- 使用指南
- [校验Mock调用](zh-cn/doc/invoke-matcher.md)
@@ -11,6 +12,7 @@
- [复用Mock类与方法](zh-cn/doc/mock-method-reusing.md)
- [使用MockWith注解](zh-cn/doc/use-mock-with.md)
- [使用包路径映射](zh-cn/doc/use-package-mapping.md)
- [使用IntelliJ插件](zh-cn/doc/use-intellij-plugin.md)
- [常见使用问题](zh-cn/doc/frequently-asked-questions.md)
- [Mock线程池内的调用](zh-cn/doc/with-thread-pool.md)
- [在IDE运行单元测试](zh-cn/doc/use-in-ide.md)

View File

@@ -6,7 +6,7 @@
<parent>
<groupId>com.alibaba.testable</groupId>
<artifactId>testable-parent</artifactId>
<version>0.7.2</version>
<version>0.7.9</version>
<relativePath>../testable-parent</relativePath>
</parent>
<artifactId>testable-agent</artifactId>
@@ -14,8 +14,8 @@
<name>testable-agent</name>
<properties>
<asm.lib.version>8.0.1</asm.lib.version>
<junit.version>5.6.2</junit.version>
<asm.lib.version>9.3</asm.lib.version>
<junit.version>5.9.1</junit.version>
</properties>
<dependencies>
@@ -123,6 +123,9 @@
<goals>
<goal>jar</goal>
</goals>
<configuration>
<additionalOptions>-Xdoclint:none</additionalOptions>
</configuration>
</execution>
</executions>
</plugin>
@@ -137,6 +140,13 @@
<goals>
<goal>sign</goal>
</goals>
<configuration>
<!-- Prevent `gpg` from using pinentry programs -->
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
</configuration>
</execution>
</executions>
</plugin>

View File

@@ -7,12 +7,15 @@ public class ConstPool {
public static final String FIELD_TARGET_METHOD = "targetMethod";
public static final String FIELD_TARGET_CLASS = "targetClass";
public static final String FIELD_TARGET_CLASS_NAME = "targetClassName";
public static final String FIELD_SCOPE = "scope";
public static final String FIELD_VALUE = "value";
public static final String FIELD_INHERITS = "inherits";
public static final String PROPERTY_USER_DIR = "user.dir";
public static final String PROPERTY_TEMP_DIR = "java.io.tmpdir";
public static final String MOCK_CONTAINER = "com.alibaba.testable.core.annotation.MockContainer";
public static final String MOCK_WITH = "com.alibaba.testable.core.annotation.MockWith";
public static final String DUMP_TO = "com.alibaba.testable.core.annotation.DumpTo";
public static final String MOCK_DIAGNOSE = "com.alibaba.testable.core.annotation.MockDiagnose";

View File

@@ -1,6 +1,5 @@
package com.alibaba.testable.agent.handler;
import com.alibaba.testable.agent.constant.ConstPool;
import com.alibaba.testable.agent.tool.ImmutablePair;
import com.alibaba.testable.agent.util.*;
import com.alibaba.testable.core.model.MockScope;
@@ -10,12 +9,16 @@ import org.objectweb.asm.Label;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.alibaba.testable.agent.constant.ByteCodeConst.TYPE_ARRAY;
import static com.alibaba.testable.agent.constant.ByteCodeConst.TYPE_CLASS;
import static com.alibaba.testable.agent.constant.ConstPool.CLASS_OBJECT;
import static com.alibaba.testable.agent.constant.ConstPool.*;
import static com.alibaba.testable.agent.util.MockInvokeUtil.*;
import static com.alibaba.testable.core.constant.ConstPool.CONSTRUCTOR;
import static com.alibaba.testable.core.util.CollectionUtil.fastListOf;
/**
* @author flin
@@ -63,9 +66,69 @@ public class MockClassHandler extends BaseClassWithContextHandler {
handleTestableUtil(mn);
}
}
// should inject inherited at last to avoid above transfers
injectInheritedMockMethods(cn);
LogUtil.diagnose(" Found %d mock methods", mockMethodCount);
}
/**
* add member field of inherited mock class by @MockContainer annotation
*/
private void injectInheritedMockMethods(ClassNode cn) {
List<Type> inheritedTypes = new ArrayList<Type>();
AnnotationNode mockContainerAnnotation = AnnotationUtil.getClassAnnotation(cn, MOCK_CONTAINER);
if (mockContainerAnnotation != null) {
inheritedTypes.addAll(AnnotationUtil.getAnnotationParameter(mockContainerAnnotation, FIELD_INHERITS,
Collections.<Type>emptyList(), List.class));
}
for (Type inheritedType : inheritedTypes) {
String className = inheritedType.getClassName();
ClassNode inheritedClassNode = ClassUtil.getClassNode(className);
if (inheritedClassNode == null) {
throw new IllegalArgumentException("Failed to load class " + className);
}
for (MethodNode mn : inheritedClassNode.methods) {
if (mn.visibleAnnotations == null) {
continue;
}
if (ClassUtil.hasMethod(cn, mn)) {
LogUtil.warn("Method '%s' with same signature already exists in class %s, skipped", mn.name, cn.name);
continue;
}
for (AnnotationNode an : mn.visibleAnnotations) {
if ((ClassUtil.toByteCodeClassName(MOCK_INVOKE)).equals(an.desc)) {
String targetClassName = getTargetClassName(an);
String targetMethod = AnnotationUtil.getAnnotationParameter(an, FIELD_TARGET_METHOD, null, String.class);
String desc = (targetClassName == null) ? mn.desc :
MethodUtil.addParameterAtBegin(mn.desc, ClassUtil.toByteCodeClassName(targetClassName));
String name = (targetMethod == null) ? mn.name : targetMethod;
MethodNode mockMethod = new MethodNode(ACC_PUBLIC, name, desc, null, null);
List<Byte> parameters = MethodUtil.getParameterTypes(mn.desc);
int maxStack = 2;
InsnList il = new InsnList();
il.add(new MethodInsnNode(INVOKESTATIC, ClassUtil.toSlashSeparatedName(className),
GET_TESTABLE_REF, VOID_ARGS + ClassUtil.toByteCodeClassName(className), false));
il.add(new VarInsnNode(ALOAD, 1));
for (int pi = 2; pi < parameters.size() + 2; pi++) {
ImmutablePair<Integer, Integer> codeAndStack = BytecodeUtil.getLoadParameterByteCode(parameters.get(pi - 2));
il.add(new VarInsnNode(codeAndStack.left, pi));
maxStack += codeAndStack.right;
}
il.add(new MethodInsnNode(INVOKEVIRTUAL, ClassUtil.toSlashSeparatedName(className), mn.name, desc, false));
il.add(new InsnNode(ARETURN));
mockMethod.instructions = il;
mockMethod.maxStack = maxStack;
mockMethod.maxLocals = 2 + parameters.size();
mockMethod.visibleAnnotations = fastListOf(new AnnotationNode(ClassUtil.toByteCodeClassName(MOCK_INVOKE)));
cn.methods.add(mockMethod);
} else if ((ClassUtil.toByteCodeClassName(MOCK_NEW)).equals(an.desc)) {
// TODO: should also support MockNew annotation
}
}
}
}
}
/**
* add method to fetch singleton instance of this mock class
*/
@@ -98,12 +161,12 @@ public class MockClassHandler extends BaseClassWithContextHandler {
private void unfoldTargetClass(MethodNode mn) {
String targetClassName = null;
for (AnnotationNode an : mn.visibleAnnotations) {
if (ClassUtil.toByteCodeClassName(ConstPool.MOCK_INVOKE).equals(an.desc)) {
Type type = AnnotationUtil.getAnnotationParameter(an, ConstPool.FIELD_TARGET_CLASS, null, Type.class);
if (type != null) {
targetClassName = ClassUtil.toByteCodeClassName(type.getClassName());
if (ClassUtil.toByteCodeClassName(MOCK_INVOKE).equals(an.desc)) {
String name = getTargetClassName(an);
if (name != null) {
targetClassName = ClassUtil.toByteCodeClassName(name);
}
AnnotationUtil.removeAnnotationParameter(an, ConstPool.FIELD_TARGET_CLASS);
AnnotationUtil.removeAnnotationParameters(an, FIELD_TARGET_CLASS, FIELD_TARGET_CLASS_NAME);
}
}
if (targetClassName != null) {
@@ -190,7 +253,10 @@ public class MockClassHandler extends BaseClassWithContextHandler {
if (VOID_RES.equals(returnType)) {
il.add(new InsnNode(POP));
il.add(new InsnNode(RETURN));
} else if (returnType.charAt(0) == TYPE_ARRAY || returnType.charAt(0) == TYPE_CLASS) {
} else if (returnType.charAt(0) == TYPE_ARRAY) {
il.add(new TypeInsnNode(CHECKCAST, returnType));
il.add(new InsnNode(ARETURN));
} else if (returnType.charAt(0) == TYPE_CLASS) {
il.add(new TypeInsnNode(CHECKCAST, ClassUtil.toSlashSeparateJavaStyleName(returnType)));
il.add(new InsnNode(ARETURN));
} else {
@@ -208,7 +274,7 @@ public class MockClassHandler extends BaseClassWithContextHandler {
String methodName = mn.name;
for (AnnotationNode an : mn.visibleAnnotations) {
if (isMockMethodAnnotation(an)) {
String name = AnnotationUtil.getAnnotationParameter(an, ConstPool.FIELD_TARGET_METHOD, null, String.class);
String name = AnnotationUtil.getAnnotationParameter(an, FIELD_TARGET_METHOD, null, String.class);
if (name != null) {
methodName = name;
}
@@ -227,7 +293,7 @@ public class MockClassHandler extends BaseClassWithContextHandler {
private boolean isGlobalScope(MethodNode mn) {
for (AnnotationNode an : mn.visibleAnnotations) {
if (isMockMethodAnnotation(an) || isMockNewAnnotation(an)) {
MockScope scope = AnnotationUtil.getAnnotationParameter(an, ConstPool.FIELD_SCOPE,
MockScope scope = AnnotationUtil.getAnnotationParameter(an, FIELD_SCOPE,
GlobalConfig.defaultMockScope, MockScope.class);
if (scope.equals(MockScope.GLOBAL)) {
return true;
@@ -243,6 +309,10 @@ public class MockClassHandler extends BaseClassWithContextHandler {
}
for (AnnotationNode an : mn.visibleAnnotations) {
if (isMockMethodAnnotation(an)) {
if (hasDuplicatedTargetClass(an)) {
throw new IllegalArgumentException("Mock method " + mn.name + " could not use both '"
+ FIELD_TARGET_CLASS + "' and '" + FIELD_TARGET_CLASS_NAME + "' parameter");
}
if (LogUtil.isVerboseEnabled()) {
LogUtil.verbose(" Mock method \"%s\" as \"%s\"", mn.name, MethodUtil.toJavaMethodDesc(
getTargetMethodOwner(mn, an), getTargetMethodName(mn, an), getTargetMethodDesc(mn, an)));
@@ -260,29 +330,26 @@ public class MockClassHandler extends BaseClassWithContextHandler {
}
private String getTargetMethodOwner(MethodNode mn, AnnotationNode mockMethodAnnotation) {
Type type = AnnotationUtil.getAnnotationParameter(mockMethodAnnotation, ConstPool.FIELD_TARGET_CLASS,
null, Type.class);
return type == null ? MethodUtil.getFirstParameter(mn.desc) : type.getClassName();
String targetClassName = getTargetClassName(mockMethodAnnotation);
return targetClassName == null ? MethodUtil.getFirstParameter(mn.desc) : targetClassName;
}
private String getTargetMethodName(MethodNode mn, AnnotationNode mockMethodAnnotation) {
String name = AnnotationUtil.getAnnotationParameter(mockMethodAnnotation, ConstPool.FIELD_TARGET_METHOD,
String name = AnnotationUtil.getAnnotationParameter(mockMethodAnnotation, FIELD_TARGET_METHOD,
null, String.class);
return name == null ? mn.name : name;
}
private String getTargetMethodDesc(MethodNode mn, AnnotationNode mockMethodAnnotation) {
Type type = AnnotationUtil.getAnnotationParameter(mockMethodAnnotation, ConstPool.FIELD_TARGET_CLASS,
null, Type.class);
return type == null ? MethodUtil.removeFirstParameter(mn.desc) : mn.desc;
return hasTargetClassParameter(mockMethodAnnotation) ? mn.desc : MethodUtil.removeFirstParameter(mn.desc);
}
private boolean isMockNewAnnotation(AnnotationNode an) {
return ClassUtil.toByteCodeClassName(ConstPool.MOCK_NEW).equals(an.desc);
return ClassUtil.toByteCodeClassName(MOCK_NEW).equals(an.desc);
}
private boolean isMockMethodAnnotation(AnnotationNode an) {
return ClassUtil.toByteCodeClassName(ConstPool.MOCK_INVOKE).equals(an.desc);
return ClassUtil.toByteCodeClassName(MOCK_INVOKE).equals(an.desc);
}
private void injectInvokeRecorder(MethodNode mn) {
@@ -324,11 +391,11 @@ public class MockClassHandler extends BaseClassWithContextHandler {
private boolean isMockForConstructor(MethodNode mn) {
for (AnnotationNode an : mn.visibleAnnotations) {
String annotationName = ClassUtil.toJavaStyleClassName(an.desc);
if (ConstPool.MOCK_NEW.equals(annotationName)) {
if (MOCK_NEW.equals(annotationName)) {
return true;
} else if (ConstPool.MOCK_INVOKE.equals(annotationName)) {
} else if (MOCK_INVOKE.equals(annotationName)) {
String method = AnnotationUtil.getAnnotationParameter
(an, ConstPool.FIELD_TARGET_METHOD, null, String.class);
(an, FIELD_TARGET_METHOD, null, String.class);
if (CONSTRUCTOR.equals(method)) {
return true;
}

View File

@@ -2,17 +2,26 @@ package com.alibaba.testable.agent.handler;
import com.alibaba.testable.agent.handler.test.JUnit4Framework;
import com.alibaba.testable.agent.handler.test.JUnit5Framework;
import com.alibaba.testable.agent.util.AnnotationUtil;
import com.alibaba.testable.agent.util.BytecodeUtil;
import com.alibaba.testable.agent.util.ClassUtil;
import com.alibaba.testable.agent.util.CollectionUtil;
import com.alibaba.testable.core.tool.CollectionTool;
import com.alibaba.testable.core.util.CollectionUtil;
import com.alibaba.testable.core.util.LogUtil;
import com.alibaba.testable.core.util.StringUtil;
import com.alibaba.testable.core.util.TypeUtil;
import org.objectweb.asm.Label;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.alibaba.testable.agent.constant.ConstPool.CLASS_OBJECT;
import static com.alibaba.testable.core.constant.ConstPool.CONSTRUCTOR;
import static com.alibaba.testable.core.constant.ConstPool.THIS_REF;
import static com.alibaba.testable.core.util.CollectionUtil.contains;
import static com.alibaba.testable.core.tool.CollectionTool.*;
/**
* @author flin
@@ -23,22 +32,28 @@ public class OmniClassHandler extends BaseClassHandler {
private static final String IGNORE = "ignore";
private static final String METHOD_START = "(";
private static final String VOID_METHOD_END = ")V";
private static final String VOID_METHOD = "()V";
private static final String ENABLE_CONFIGURATION = "Lorg/springframework/context/annotation/Configuration;";
private static final String CLASS_ABSTRACT_COLLECTION = "java/util/AbstractCollection";
private static final String CLASS_NUMBER = "java/lang/Number";
private static final String CLASS_HASH_SET = "java/util/HashSet";
private static final String ENABLE_CONFIGURATION = "org.springframework.context.annotation.Configuration";
private static final String CLASS_OMNI_CONSTRUCTOR = "com/alibaba/testable/core/tool/OmniConstructor";
public static final String CLASS_CONSTRUCTION_OPTION = "com/alibaba/testable/core/model/ConstructionOption";
public static final String METHOD_NEW_INSTANCE = "newInstance";
public static final String METHOD_DESC_NEW_INSTANCE = "(Ljava/lang/Class;[Lcom/alibaba/testable/core/model/ConstructionOption;)Ljava/lang/Object;";
// below classes are loaded before OmniClassHandler, cannot be instrumented
// map of class name to constructor parameters
private static final Map<String, String[]> PRELOADED_CLASSES = mapOf(
entryOf(CLASS_OBJECT, CollectionTool.<String>arrayOf())
);
private static final String[] JUNIT_TEST_ANNOTATIONS = new String[] {
JUnit4Framework.ANNOTATION_TEST, JUnit5Framework.ANNOTATION_TEST, JUnit5Framework.ANNOTATION_PARAMETERIZED_TEST
};
private static final String[] UNREACHABLE_CLASSES = new String[] {
CLASS_ABSTRACT_COLLECTION, CLASS_NUMBER, CLASS_HASH_SET
};
private static final Map<String, Class<?>[]> constructorParameterCache = new HashMap<String, Class<?>[]>();
@Override
protected void transform(ClassNode cn) {
if (isInterfaceOrAtom(cn) || isJunitTestClass(cn) || isUninstantiableClass(cn) || hasSpecialAnnotation(cn)) {
if (isInterfaceOrAtom(cn) || isUniqueConstructorClass(cn) || isUninstantiableClass(cn) ||
AnnotationUtil.getClassAnnotation(cn, ENABLE_CONFIGURATION) != null) {
return;
}
addConstructorWithVoidTypeParameter(cn);
@@ -49,29 +64,56 @@ public class OmniClassHandler extends BaseClassHandler {
METHOD_START + ClassUtil.toByteCodeClassName(VOID_TYPE) + VOID_METHOD_END, null, null);
LabelNode start = new LabelNode(new Label());
LabelNode end = new LabelNode(new Label());
if (cn.superName.equals(CLASS_OBJECT)) {
constructor.instructions = invokeSuperWithoutParameter(start, end);
constructor.localVariables = createLocalVariables(cn, start, end);
constructor.maxStack = 1;
int extraParameterCount = 2;
if (PRELOADED_CLASSES.containsKey(cn.superName)) {
constructor.instructions = invokeSuperWithoutTestableParameter(cn.superName, PRELOADED_CLASSES.get(cn.superName), start, end);
extraParameterCount = PRELOADED_CLASSES.get(cn.superName).length;
} else if (cn.superName.startsWith("java/")) {
try {
Class<?>[] constructorParameterTypes = constructorParameterCache.get(cn.superName);
if (constructorParameterTypes == null) {
Class<?> superClazz = Class.forName(ClassUtil.toDotSeparatedName(cn.superName));
constructorParameterTypes = TypeUtil.getBestConstructor(superClazz).getParameterTypes();
constructorParameterCache.put(superClazz.getName(), constructorParameterTypes);
}
if (constructorParameterTypes.length == 0) {
constructor.instructions = invokeSuperWithoutTestableParameter(cn.superName, new String[0], start, end);
extraParameterCount = 0;
} else if (constructorParameterTypes.length == 1 &&
constructorParameterTypes[0].equals(Void.class)) {
constructor.instructions = invokeSuperWithTestableVoidParameter(cn.superName, start, end);
} else {
constructor.instructions = invokeSuperWithoutTestableParameter(cn.superName,
toByteCodeClassNames(constructorParameterTypes), start, end);
extraParameterCount = constructorParameterTypes.length;
}
} catch (ClassNotFoundException e) {
LogUtil.warn("[OmniConstructor] Failed to load class " + cn.superName);
constructor.instructions = invokeSuperWithoutTestableParameter(cn.superName, new String[0], start, end);
}
} else {
constructor.instructions = invokeSuperWithTestableVoidParameter(cn, start, end);
constructor.localVariables = createLocalVariables(cn, start, end);
constructor.maxStack = 3;
constructor.instructions = invokeSuperWithTestableVoidParameter(cn.superName, start, end);
}
constructor.localVariables = createLocalVariables(cn, start, end);
constructor.maxStack = 1 + extraParameterCount;
constructor.maxLocals = 2;
cn.methods.add(constructor);
}
private boolean hasSpecialAnnotation(ClassNode cn) {
if (cn.visibleAnnotations == null) {
return false;
}
for (AnnotationNode an : cn.visibleAnnotations) {
if (an.desc.equals(ENABLE_CONFIGURATION)) {
return true;
private String[] toByteCodeClassNames(Class<?>[] classes) {
String[] names = new String[classes.length];
for (int i = 0; i < names.length; i++) {
if (classes[i].isPrimitive()) {
names[i] = BytecodeUtil.PRIMITIVE_TYPE_NAME_MAP.get(classes[i].getName());
} else if (classes[i].isArray()) {
names[i] = ClassUtil.toSlashSeparatedName(classes[i].getName());
} else {
names[i] = ClassUtil.toByteCodeClassName(classes[i].getName());
}
}
return false;
return names;
}
private boolean isUninstantiableClass(ClassNode cn) {
@@ -89,14 +131,22 @@ public class OmniClassHandler extends BaseClassHandler {
return (cn.access & ACC_INTERFACE) != 0 || cn.superName == null || VOID_TYPE.equals(cn.name);
}
private boolean isJunitTestClass(ClassNode cn) {
private boolean isUniqueConstructorClass(ClassNode cn) {
// elastic plugin class should contain only one constructor
if ("org/elasticsearch/plugins/Plugin".equals(cn.superName)) {
return true;
}
// should skip mockito generated class
if (cn.name.contains("$MockitoMock$")) {
return true;
}
// junit require test class contains only one constructor
for (MethodNode mn : cn.methods) {
if (mn.visibleAnnotations == null) {
continue;
}
for (AnnotationNode an : mn.visibleAnnotations) {
if (contains(JUNIT_TEST_ANNOTATIONS, an.desc)) {
if (CollectionUtil.contains(JUNIT_TEST_ANNOTATIONS, an.desc)) {
return true;
}
}
@@ -104,34 +154,38 @@ public class OmniClassHandler extends BaseClassHandler {
return false;
}
private InsnList invokeSuperWithoutParameter(LabelNode start, LabelNode end) {
private InsnList invokeSuperWithoutTestableParameter(String superName, String[] parameters, LabelNode start, LabelNode end) {
InsnList il = new InsnList();
il.add(start);
il.add(new VarInsnNode(ALOAD, 0));
il.add(new MethodInsnNode(INVOKESPECIAL, CLASS_OBJECT, CONSTRUCTOR, VOID_METHOD, false));
for (String p : parameters) {
il.add(new LdcInsnNode(Type.getType(p)));
il.add(new InsnNode(ICONST_0));
il.add(new TypeInsnNode(ANEWARRAY, CLASS_CONSTRUCTION_OPTION));
il.add(new MethodInsnNode(INVOKESTATIC, CLASS_OMNI_CONSTRUCTOR, METHOD_NEW_INSTANCE, METHOD_DESC_NEW_INSTANCE, false));
il.add(new TypeInsnNode(CHECKCAST, (p.startsWith("[")) ? p : ClassUtil.toSlashSeparateJavaStyleName(p)));
}
il.add(new MethodInsnNode(INVOKESPECIAL, superName, CONSTRUCTOR,
METHOD_START + StringUtil.join("", parameters) + VOID_METHOD_END, false));
il.add(new InsnNode(RETURN));
il.add(end);
return il;
}
private InsnList invokeSuperWithTestableVoidParameter(ClassNode cn, LabelNode start, LabelNode end) {
private InsnList invokeSuperWithTestableVoidParameter(String superName, LabelNode start, LabelNode end) {
InsnList il = new InsnList();
il.add(start);
il.add(new VarInsnNode(ALOAD, 0));
if (contains(UNREACHABLE_CLASSES, cn.superName)) {
il.add(new MethodInsnNode(INVOKESPECIAL, cn.superName, CONSTRUCTOR, VOID_METHOD, false));
} else {
il.add(new VarInsnNode(ALOAD, 1));
il.add(new MethodInsnNode(INVOKESPECIAL, cn.superName, CONSTRUCTOR,
METHOD_START + ClassUtil.toByteCodeClassName(VOID_TYPE) + VOID_METHOD_END, false));
}
il.add(new VarInsnNode(ALOAD, 1));
il.add(new MethodInsnNode(INVOKESPECIAL, superName, CONSTRUCTOR,
METHOD_START + ClassUtil.toByteCodeClassName(VOID_TYPE) + VOID_METHOD_END, false));
il.add(new InsnNode(RETURN));
il.add(end);
return il;
}
private List<LocalVariableNode> createLocalVariables(ClassNode cn, LabelNode start, LabelNode end) {
return CollectionUtil.listOf(
return listOf(
new LocalVariableNode(THIS_REF, ClassUtil.toByteCodeClassName(cn.name), null, start, end, 0),
new LocalVariableNode(IGNORE, ClassUtil.toByteCodeClassName(VOID_TYPE), null, start, end, 1)
);

View File

@@ -1,27 +1,21 @@
package com.alibaba.testable.agent.handler;
import com.alibaba.testable.agent.model.BasicType;
import com.alibaba.testable.agent.model.BsmArg;
import com.alibaba.testable.agent.model.MethodInfo;
import com.alibaba.testable.agent.model.TravelStatus;
import com.alibaba.testable.agent.util.BytecodeUtil;
import com.alibaba.testable.agent.util.ClassUtil;
import com.alibaba.testable.agent.util.MethodUtil;
import com.alibaba.testable.core.util.LogUtil;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.*;
import org.objectweb.asm.tree.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import static com.alibaba.testable.core.constant.ConstPool.CONSTRUCTOR;
import static com.alibaba.testable.core.constant.ConstPool.DOLLAR;
/**
* @author flin
@@ -51,6 +45,10 @@ public class SourceClassHandler extends BaseClassHandler {
@Override
protected void transform(ClassNode cn) {
LogUtil.diagnose("Found source class %s", cn.name);
if (injectMethods.isEmpty()) {
return;
}
Set<MethodInfo> memberInjectMethods = new HashSet<MethodInfo>();
Set<MethodInfo> newOperatorInjectMethods = new HashSet<MethodInfo>();
for (MethodInfo im : injectMethods) {
@@ -61,17 +59,19 @@ public class SourceClassHandler extends BaseClassHandler {
}
}
resolveMethodReference(cn);
if (!memberInjectMethods.isEmpty()) {
resolveMethodReference(cn, memberInjectMethods);
}
for (MethodNode m : cn.methods) {
transformMethod(m, memberInjectMethods, newOperatorInjectMethods, cn);
transformMethod(m, memberInjectMethods, newOperatorInjectMethods);
}
}
private void transformMethod(MethodNode mn, Set<MethodInfo> memberInjectMethods,
Set<MethodInfo> newOperatorInjectMethods, ClassNode cn) {
Set<MethodInfo> newOperatorInjectMethods) {
LogUtil.verbose(" Found method %s", mn.name);
if (mn.name.startsWith("$")) {
if (mn.name.startsWith(DOLLAR)) {
// skip methods e.g. "$jacocoInit"
return;
}
@@ -341,85 +341,57 @@ public class SourceClassHandler extends BaseClassHandler {
return Opcodes.INVOKEVIRTUAL == opcode && ClassUtil.isCompanionClassName(ownerClass);
}
private void setFinalValue(Field ownerField, Object obj, Object value) throws Exception {
ownerField.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(ownerField, ownerField.getModifiers() & ~Modifier.FINAL);
ownerField.set(obj, value);
}
private List<Handle> fetchInvokeDynamicHandle(MethodNode mn) {
List<Handle> handleList = new ArrayList<Handle>();
private List<BsmArg> fetchInvokeDynamicHandle(MethodNode mn) {
List<BsmArg> handleList = new ArrayList<BsmArg>();
for (AbstractInsnNode instruction : mn.instructions) {
if (instruction.getOpcode() == Opcodes.INVOKEDYNAMIC) {
InvokeDynamicInsnNode invokeDynamicInsnNode = (InvokeDynamicInsnNode) instruction;
handleList.add((Handle) invokeDynamicInsnNode.bsmArgs[1]);
// java9+ String makeConcatWithConstants will ues INVOKEDYNAMIC to optimize.
// When the mock source method has like <code>"abc" + "def"</code> the bsmArgs length was 1
// https://openjdk.java.net/jeps/280
if (invokeDynamicInsnNode.bsmArgs.length < 3) {
continue;
}
BsmArg bsmArg = new BsmArg(invokeDynamicInsnNode.bsmArgs);
handleList.add(bsmArg);
}
}
return handleList;
}
private void resolveMethodReference(ClassNode cn) {
List<Handle> invokeDynamicList = new ArrayList<Handle>();
private void resolveMethodReference(ClassNode cn, Set<MethodInfo> mockedMethods) {
List<BsmArg> invokeDynamicList = new ArrayList<BsmArg>();
for (MethodNode method : cn.methods) {
List<Handle> handleList = fetchInvokeDynamicHandle(method);
invokeDynamicList.addAll(handleList);
List<BsmArg> handleList = fetchInvokeDynamicHandle(method);
for (BsmArg arg : handleList) {
for (MethodInfo mi : mockedMethods) {
if (isMethodMocked(arg.getHandle(), mi)) {
invokeDynamicList.add(arg);
}
}
}
}
// process for method reference
for (Handle handle : invokeDynamicList) {
for (BsmArg bsmArg : invokeDynamicList) {
// the jdk auto generation method
if (handle.getName().startsWith("lambda$")) {
if (bsmArg.getHandle().getName().startsWith("lambda$")) {
continue;
}
int tag = handle.getTag();
int tag = bsmArg.getHandle().getTag();
if (tag == Opcodes.H_NEWINVOKESPECIAL) {
// lambda new method reference
continue;
}
// external mean:
// public void foo() {
// String s = "";
// consumes(s::contains);
//}
boolean external = tag == Opcodes.H_INVOKEVIRTUAL;
boolean isStatic = bsmArg.isStatic();
Handle handle = bsmArg.getHandle();
Type handleDesc = bsmArg.getHandleDesc();
boolean isStatic = tag == Opcodes.H_INVOKESTATIC || external;
String desc = handle.getDesc();
String parameters = desc.substring(desc.indexOf("(") + 1, desc.lastIndexOf(")"));
String returnType = desc.substring(desc.indexOf(")") + 1);
String[] parameterArray = parameters.split(";");
int len = parameterArray.length;
for (String s : parameterArray) {
if (s.isEmpty()) {
len--;
}
}
len = external ? len + 1 : len;
String[] refineParameterArray = new String[len];
int index = external ? 1 : 0;
if (external) {
// The type should was reference type
refineParameterArray[0] = "L" + handle.getOwner();
}
for (String s : parameterArray) {
if (!s.isEmpty()) {
refineParameterArray[index] = s;
index++;
}
}
String externalDesc = buildDesc(refineParameterArray, returnType);
String lambdaName = String.format("Lambda$_%s_%d", handle.getName(), atomicInteger.incrementAndGet());
MethodVisitor mv = cn.visitMethod(isStatic ? ACC_PUBLIC + ACC_STATIC : ACC_PUBLIC, lambdaName, external ? externalDesc : desc, null, null);
String lambdaName = String.format("_Lambda$_%s_%d", handle.getName(), atomicInteger.incrementAndGet());
MethodVisitor mv = cn.visitMethod(isStatic ? ACC_PUBLIC + ACC_STATIC : ACC_PUBLIC, lambdaName, handleDesc.getDescriptor(), null, null);
mv.visitCode();
Label l0 = new Label();
@@ -428,102 +400,65 @@ public class SourceClassHandler extends BaseClassHandler {
// add this
mv.visitVarInsn(ALOAD, 0);
}
for (int i = 0; i < refineParameterArray.length; i++) {
String arg = refineParameterArray[i];
mv.visitVarInsn(getLoadType(arg), isStatic ? i : i + 1);
Type[] argumentTypes = handleDesc.getArgumentTypes();
int nextVar = isStatic ? 0 : 1;
for (Type argumentType : argumentTypes) {
String arg = argumentType.getDescriptor();
mv.visitVarInsn(getLoadType(arg), nextVar);
nextVar = isLongByte(argumentType) ? nextVar + 2 : nextVar + 1;
}
// the method call is static ?
mv.visitMethodInsn(Opcodes.H_INVOKESTATIC == tag ? INVOKESTATIC : INVOKEVIRTUAL, handle.getOwner(), handle.getName(), desc, false);
if (tag == H_INVOKEINTERFACE) {
mv.visitMethodInsn(INVOKEINTERFACE, handle.getOwner(), handle.getName(), bsmArg.getOriginalHandleDesc(), handle.isInterface());
} else {
mv.visitMethodInsn(Opcodes.H_INVOKESTATIC == tag ? INVOKESTATIC : INVOKEVIRTUAL, handle.getOwner(), handle.getName(), bsmArg.getOriginalHandleDesc(), handle.isInterface());
}
mv.visitInsn(getReturnType(returnType));
mv.visitInsn(getReturnType(handleDesc.getReturnType().getDescriptor()));
Label l1 = new Label();
mv.visitLabel(l1);
// static function was not required add this to first parameter
if (isStatic) {
for (int i = 0; i < refineParameterArray.length; i++) {
String localVar = refineParameterArray[i];
if (!isPrimitive(localVar)) {
// primitive type and reference type difference
localVar = localVar.endsWith(";") ? localVar : localVar + ";";
}
if (localVar.isEmpty()) {
continue;
}
// add local var
mv.visitLocalVariable(String.format("o%d", i), localVar, null, l0, l1, i);
}
visitLocalVariableByArguments(mv, 0, argumentTypes, l0, l1);
} else {
mv.visitLocalVariable("this", "L" + handle.getOwner() + ";", null, l0, l1, 0);
for (int i = 0; i < refineParameterArray.length; i++) {
String localVar = refineParameterArray[i];
if (!isPrimitive(localVar) && !isPrimitiveArray(localVar)) {
localVar = localVar.endsWith(";") ? localVar : localVar + ";";
}
if (localVar.isEmpty()) {
continue;
}
mv.visitLocalVariable(String.format("o%d", i), localVar, null, l0, l1, i + 1);
}
visitLocalVariableByArguments(mv, 1, argumentTypes, l0, l1);
}
// auto compute max
mv.visitMaxs(-1, -1);
mv.visitEnd();
try {
// modify handle to the generation method
setFinalValue(handle.getClass().getDeclaredField("name"), handle, lambdaName);
// mark: should merge the below two if.
if (!handle.getOwner().equals(cn.name) && isStatic) {
setFinalValue(handle.getClass().getDeclaredField("owner"), handle, cn.name);
}
if (external) {
setFinalValue(handle.getClass().getDeclaredField("owner"), handle, cn.name);
setFinalValue(handle.getClass().getDeclaredField("descriptor"), handle, externalDesc);
setFinalValue(handle.getClass().getDeclaredField("tag"), handle, H_INVOKESTATIC);
}
} catch (Exception ignore) {
}
bsmArg.complete(cn.name, lambdaName);
}
}
private String buildDesc(String[] refineParameterArray, String returnType) {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (String s : refineParameterArray) {
sb.append(s);
if (!isPrimitive(s)) {
sb.append(";");
}
private boolean isMethodMocked(Handle targetHandle, MethodInfo mockMethodInfo) {
if (targetHandle.getTag() == Opcodes.H_INVOKEINTERFACE || targetHandle.getTag() == Opcodes.H_INVOKEVIRTUAL) {
String targetMockDesc = MethodUtil.addParameterAtBegin(mockMethodInfo.getDesc(),
ClassUtil.toByteCodeClassName(mockMethodInfo.getClazz()));
return mockMethodInfo.getClazz().equals(targetHandle.getOwner()) &&
mockMethodInfo.getName().equals(targetHandle.getName()) &&
targetMockDesc.equals(targetHandle.getDesc());
}
sb.append(")");
sb.append(returnType);
return sb.toString();
return mockMethodInfo.getClazz().equals(targetHandle.getOwner()) &&
mockMethodInfo.getName().equals(targetHandle.getName()) &&
mockMethodInfo.getDesc().equals(targetHandle.getDesc());
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean isPrimitive(String type) {
if (type.endsWith(";")) {
type = type.substring(0, type.length() - 1);
private void visitLocalVariableByArguments(MethodVisitor mv, final int initVar, Type[] argumentTypes, Label l0, Label l1) {
int nextLocalVar = initVar;
for (int i = 0; i < argumentTypes.length; i++) {
Type argumentType = argumentTypes[i];
String localVar = argumentType.getDescriptor();
mv.visitLocalVariable(String.format("o%d", i), localVar, null, l0, l1, nextLocalVar);
nextLocalVar = isLongByte(argumentType) ? nextLocalVar + 2 : nextLocalVar + 1;
}
return BasicType.basicType(type.charAt(0)).isPrimitive();
}
private boolean isPrimitiveArray(String type) {
if (!type.startsWith("[")) {
return false;
}
if (type.endsWith(";")) {
type = type.substring(0, type.length() - 1);
}
type = type.replace("[", "");
return BasicType.basicType(type.charAt(0)).isPrimitive();
private boolean isLongByte(Type argumentType) {
return double.class.getName().equals(argumentType.getClassName()) || long.class.getName().equals(argumentType.getClassName());
}
private int getReturnType(String returnType) {

View File

@@ -2,7 +2,7 @@ package com.alibaba.testable.agent.handler.test;
import com.alibaba.testable.agent.model.TestCaseMethodType;
import com.alibaba.testable.agent.util.ClassUtil;
import com.alibaba.testable.agent.util.CollectionUtil;
import com.alibaba.testable.core.util.CollectionUtil;
import org.objectweb.asm.Label;
import org.objectweb.asm.tree.*;

View File

@@ -1,7 +1,7 @@
package com.alibaba.testable.agent.handler.test;
import com.alibaba.testable.agent.model.TestCaseMethodType;
import com.alibaba.testable.agent.util.CollectionUtil;
import com.alibaba.testable.core.util.CollectionUtil;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.MethodNode;

View File

@@ -0,0 +1,84 @@
package com.alibaba.testable.agent.model;
import com.alibaba.testable.core.util.StringUtil;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
/**
* @author jim
*/
public class BsmArg {
private Type handleDesc;
private Type methodDesc;
private Handle handle;
private final Object[] bsmArgs;
private final String originalHandleDesc;
public BsmArg(Object[] bsmArgs) {
this.bsmArgs = bsmArgs;
handle = (Handle) bsmArgs[1];
methodDesc = (Type) bsmArgs[2];
handleDesc = Type.getType(handle.getDesc());
originalHandleDesc = handle.getDesc();
// H_INVOKEVIRTUAL: String s = "";consumes(s::contains);
// H_INVOKEINTERFACE: list.stream().flatMap(Collection::stream)
if (handle.getTag() == Opcodes.H_INVOKEVIRTUAL || handle.getTag() == Opcodes.H_INVOKEINTERFACE) {
Type[] argumentTypes = handleDesc.getArgumentTypes();
Type thisArgument = Type.getType("L" + handle.getOwner() + ";");
String handleDescString = refineHandle(thisArgument, argumentTypes);
handle = new Handle(handle.getTag(), handle.getOwner(), handle.getName(), handleDescString, handle.isInterface());
handleDesc = Type.getType(handleDescString);
if (/*handle.getTag() == Opcodes.H_INVOKEVIRTUAL || */methodDesc.getArgumentTypes().length == handleDesc.getArgumentTypes().length - 1) {
Type[] methodArguments = methodDesc.getArgumentTypes();
String methodDescString = refineHandle(thisArgument, methodArguments);
methodDesc = Type.getType(methodDescString);
}
}
}
private String refineHandle(Type thisArgument, Type[] argumentTypes) {
Type[] handleArguments = new Type[argumentTypes.length + 1];
String[] handleArgs = new String[argumentTypes.length + 1];
handleArguments[0] = thisArgument;
System.arraycopy(argumentTypes, 0, handleArguments, 1, argumentTypes.length);
for (int i = 0; i < handleArguments.length; i++) {
handleArgs[i] = handleArguments[i].getDescriptor();
}
return "(" + StringUtil.join("", handleArgs) + ")" + handleDesc.getReturnType().getDescriptor();
}
public Type getHandleDesc() {
return handleDesc;
}
public Type getMethodDesc() {
return methodDesc;
}
public Handle getHandle() {
return handle;
}
public String getOriginalHandleDesc() {
return originalHandleDesc;
}
public boolean isStatic() {
int tag = handle.getTag();
return tag == Opcodes.H_INVOKESTATIC || tag == Opcodes.H_INVOKEVIRTUAL || tag == Opcodes.H_INVOKEINTERFACE;
}
public void complete(String owner, String methodName) {
bsmArgs[1] = new Handle(isStatic()? Opcodes.H_INVOKESTATIC : Opcodes.H_INVOKEVIRTUAL, owner, methodName, handleDesc.getDescriptor(), false);
}
}

View File

@@ -13,13 +13,15 @@ import org.objectweb.asm.tree.InnerClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.alibaba.testable.agent.constant.ByteCodeConst.TYPE_CLASS;
import static com.alibaba.testable.agent.constant.ConstPool.CLASS_OBJECT;
import static com.alibaba.testable.agent.constant.ConstPool.KOTLIN_POSTFIX_COMPANION;
import static com.alibaba.testable.agent.constant.ConstPool.*;
import static com.alibaba.testable.agent.util.ClassUtil.toJavaStyleClassName;
import static com.alibaba.testable.agent.util.MethodUtil.isStatic;
import static com.alibaba.testable.agent.util.MockInvokeUtil.getTargetClassName;
import static com.alibaba.testable.agent.util.MockInvokeUtil.hasTargetClassParameter;
import static com.alibaba.testable.core.constant.ConstPool.CONSTRUCTOR;
import static com.alibaba.testable.core.constant.ConstPool.MOCK_POSTFIX;
@@ -39,13 +41,14 @@ public class MockClassParser {
for (MethodNode mn : getAllMethods(cn)) {
addMethodWithAnnotationCheck(methodInfos, cn, mn);
}
handleMockContainerInherits(methodInfos, cn);
return methodInfos;
}
/**
* Check whether any method in specified class has mock-related annotation
* Check whether specified class is declared as mock container or has any method with mock-related annotation
*
* @param cn class that need to explore
* @param cn class to explore
* @return found annotation or not
*/
public boolean isMockClass(ClassNode cn) {
@@ -53,6 +56,9 @@ public class MockClassParser {
return false;
}
DiagnoseUtil.setupByClass(cn);
if (AnnotationUtil.getClassAnnotation(cn, MOCK_CONTAINER) != null) {
return true;
}
for (MethodNode mn : cn.name.endsWith(MOCK_POSTFIX) ? getAllMethods(cn) : cn.methods) {
if (mn.visibleAnnotations != null) {
for (AnnotationNode an : mn.visibleAnnotations) {
@@ -92,6 +98,27 @@ public class MockClassParser {
return mns;
}
/**
* Take care of @MockContainer annotation
*/
private void handleMockContainerInherits(List<MethodInfo> methodInfos, ClassNode cn) {
AnnotationNode an = AnnotationUtil.getClassAnnotation(cn, MOCK_CONTAINER);
if (an != null) {
for (Object st : AnnotationUtil.getAnnotationParameter(an, FIELD_INHERITS,
Collections.<Type>emptyList(), List.class)) {
String superClassName = ((Type)st).getClassName();
ClassNode superCn = ClassUtil.getClassNode(superClassName);
if (superCn == null) {
LogUtil.warn("failed to load class '%s' inherited by '%s'", superClassName, cn.name);
continue;
}
for (MethodNode mn : getAllMethods(superCn)) {
addMethodWithAnnotationCheck(methodInfos, cn, mn);
}
}
}
}
private void addMethodWithAnnotationCheck(List<MethodInfo> methodInfos, ClassNode cn, MethodNode mn) {
if (mn.visibleAnnotations == null) {
return;
@@ -122,9 +149,9 @@ public class MockClassParser {
}
private MethodInfo getMethodInfo(ClassNode cn, MethodNode mn, AnnotationNode an, String targetMethod) {
Type targetType = AnnotationUtil.getAnnotationParameter(an, ConstPool.FIELD_TARGET_CLASS, null, Type.class);
String targetTypeName = getTargetClassName(an);
boolean isStatic = isStatic(mn);
if (targetType == null) {
if (targetTypeName == null) {
// "targetClass" unset, use first parameter as target class type
ImmutablePair<String, String> methodDescPair = MethodUtil.splitFirstAndRestParameters(mn.desc);
if (methodDescPair.left.isEmpty()) {
@@ -134,7 +161,7 @@ public class MockClassParser {
isStatic);
} else {
// "targetClass" found, use it as target class type
String slashSeparatedName = ClassUtil.toSlashSeparatedName(targetType.getClassName());
String slashSeparatedName = ClassUtil.toSlashSeparatedName(targetTypeName);
return new MethodInfo(slashSeparatedName, targetMethod, mn.desc, cn.name, mn.name,
MethodUtil.addParameterAtBegin(mn.desc, ClassUtil.toByteCodeClassName(slashSeparatedName)), isStatic);
}
@@ -145,11 +172,9 @@ public class MockClassParser {
if (targetMethodName == null) {
targetMethodName = mn.name;
}
String targetClassName;
String targetMethodDesc;
Type targetClass = AnnotationUtil.getAnnotationParameter(an, ConstPool.FIELD_TARGET_CLASS, null, Type.class);
if (targetClass != null) {
targetClassName = targetClass.getClassName();
String targetClassName = getTargetClassName(an);
if (targetClassName != null) {
targetMethodDesc = mn.desc;
checkMethodExists(cn.name, mn.name, targetClassName, targetMethodName, targetMethodDesc);
} else if (mn.desc.charAt(1) == TYPE_CLASS) {
@@ -207,8 +232,7 @@ public class MockClassParser {
* @return valid or not
*/
private boolean isValidMockMethod(MethodNode mn, AnnotationNode an) {
Type targetClass = AnnotationUtil.getAnnotationParameter(an, ConstPool.FIELD_TARGET_CLASS, null, Type.class);
if (targetClass != null) {
if (hasTargetClassParameter(an)) {
return true;
}
String firstParameter = MethodUtil.getFirstParameter(mn.desc);

View File

@@ -19,8 +19,7 @@ import java.lang.instrument.ClassFileTransformer;
import java.security.ProtectionDomain;
import java.util.List;
import static com.alibaba.testable.agent.constant.ConstPool.CGLIB_CLASS_PATTERN;
import static com.alibaba.testable.agent.constant.ConstPool.KOTLIN_POSTFIX_COMPANION;
import static com.alibaba.testable.agent.constant.ConstPool.*;
import static com.alibaba.testable.core.constant.ConstPool.DOLLAR;
import static com.alibaba.testable.core.constant.ConstPool.TEST_POSTFIX;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
@@ -31,7 +30,7 @@ import static org.objectweb.asm.Opcodes.ACC_STATIC;
public class TestableClassTransformer implements ClassFileTransformer {
private static final String FIELD_TREAT_AS = "treatAs";
private static final String CLASS_JUNIT_5_NESTED = "Lorg/junit/jupiter/api/Nested;";
private static final String CLASS_JUNIT_5_NESTED = "org.junit.jupiter.api.Nested";
/**
* Just avoid spend time to scan those surely non-user classes, should keep these lists as tiny as possible
@@ -103,14 +102,17 @@ public class TestableClassTransformer implements ClassFileTransformer {
private String foundMockForSourceClass(String name) {
String className = (GlobalConfig.getMockPackageMapping() == null) ? name : mapPackage(name);
// handle @MockWith annotation on source class
String mockClass = lookForMockWithAnnotationAsSourceClass(className);
if (mockClass != null) {
return mockClass;
}
mockClass = foundMockForTestClass(ClassUtil.getTestClassName(className));
// look for [ThisClass]Test.Mock, [ThisClass]Mock and class with @MockContainer annotation
mockClass = foundMockForStandardClass(className);
if (mockClass != null) {
return mockClass;
}
// inner class should also look for mock class in the test class of its outer class
return foundMockForInnerSourceClass(className);
}
@@ -127,38 +129,36 @@ public class TestableClassTransformer implements ClassFileTransformer {
private String foundMockForInnerSourceClass(String className) {
return (className.contains(DOLLAR) && !className.endsWith(KOTLIN_POSTFIX_COMPANION)) ?
foundMockForTestClass(ClassUtil.getTestClassName(className.substring(0, className.indexOf(DOLLAR)))) : null;
foundMockForStandardClass(className.substring(0, className.indexOf(DOLLAR))) : null;
}
private String foundMockForTestClass(String className) {
ClassNode cn = adaptInnerClass(ClassUtil.getClassNode(className));
private String foundMockForStandardClass(String className) {
ClassNode cn = adaptInnerClass(ClassUtil.getClassNode(ClassUtil.getTestClassName(className)));
if (cn != null) {
// handle @MockWith annotation on test class
String mockClass = lookForMockWithAnnotationAsTestClass(cn);
if (mockClass != null) {
return mockClass;
}
// look for [ThisClass]Test.Mock or @MockContainer annotation
mockClass = lookForInnerMockClass(cn);
if (mockClass != null) {
return mockClass;
}
}
// look for [ThisClass]Mock
return lookForOuterMockClass(className);
}
private ClassNode adaptInnerClass(ClassNode cn) {
if (cn == null || cn.visibleAnnotations == null) {
return cn;
}
for (AnnotationNode an : cn.visibleAnnotations) {
if (an.desc.equals(CLASS_JUNIT_5_NESTED)) {
return ClassUtil.getClassNode(ClassUtil.toOuterClassName(cn.name));
}
if (AnnotationUtil.getClassAnnotation(cn, CLASS_JUNIT_5_NESTED) != null) {
return ClassUtil.getClassNode(ClassUtil.toOuterClassName(cn.name));
}
return cn;
}
private String lookForOuterMockClass(String className) {
String mockClassName = ClassUtil.getMockClassName(ClassUtil.getSourceClassName(className));
String mockClassName = ClassUtil.getMockClassName(className);
if (mockClassParser.isMockClass(ClassUtil.getClassNode(mockClassName))) {
return mockClassName;
}
@@ -214,7 +214,9 @@ public class TestableClassTransformer implements ClassFileTransformer {
private String lookForInnerMockClass(ClassNode cn) {
for (InnerClassNode ic : cn.innerClasses) {
ClassNode innerClassNode = ClassUtil.getClassNode(ic.name);
if (ic.name.equals(getInnerMockClassName(cn.name)) && mockClassParser.isMockClass(innerClassNode)) {
boolean isNameMatched = ic.name.equals(getInnerMockClassName(cn.name)) ||
AnnotationUtil.getClassAnnotation(innerClassNode, MOCK_CONTAINER) != null;
if (isNameMatched && mockClassParser.isMockClass(innerClassNode)) {
if ((ic.access & ACC_STATIC) == 0) {
LogUtil.warn("Mock class in \"%s\" is not declared as static", cn.name);
} else {
@@ -248,18 +250,15 @@ public class TestableClassTransformer implements ClassFileTransformer {
* @return mock class name
*/
private String parseMockWithAnnotation(ClassNode cn, ClassType expectedType) {
if (cn.visibleAnnotations != null) {
for (AnnotationNode an : cn.visibleAnnotations) {
if ((ClassUtil.toByteCodeClassName(ConstPool.MOCK_WITH)).equals(an.desc)) {
ClassType type = AnnotationUtil.getAnnotationParameter(an, FIELD_TREAT_AS, ClassType.GuessByName,
ClassType.class);
if (isExpectedType(cn.name, type, expectedType)) {
Type clazz = AnnotationUtil.getAnnotationParameter(an, ConstPool.FIELD_VALUE,
Type.getType(NullType.class), Type.class);
DiagnoseUtil.setupByClass(ClassUtil.getClassNode(clazz.getClassName()));
return clazz.getClassName();
}
}
AnnotationNode an = AnnotationUtil.getClassAnnotation(cn, MOCK_WITH);
if (an != null) {
ClassType type = AnnotationUtil.getAnnotationParameter(an, FIELD_TREAT_AS, ClassType.GuessByName,
ClassType.class);
if (isExpectedType(cn.name, type, expectedType)) {
Type clazz = AnnotationUtil.getAnnotationParameter(an, ConstPool.FIELD_VALUE,
Type.getType(NullType.class), Type.class);
DiagnoseUtil.setupByClass(ClassUtil.getClassNode(clazz.getClassName()));
return clazz.getClassName();
}
}
return null;

View File

@@ -1,6 +1,7 @@
package com.alibaba.testable.agent.util;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
/**
* @author flin
@@ -41,23 +42,85 @@ public class AnnotationUtil {
}
/**
* Remove specified parameter from annotation
* @param an annotation node
* @param key name of parameter to remove
* @return true - success, false - not found
* Check whether annotation has any of the specified parameters
* @param an annotation to check
* @param keys name of parameters
* @return yes or no
*/
public static boolean removeAnnotationParameter(AnnotationNode an, String key) {
if (an.values == null) {
return false;
}
for (int i = 0; i < an.values.size(); i += 2) {
if (an.values.get(i).equals(key)) {
an.values.remove(i + 1);
an.values.remove(i);
return true;
public static boolean hasAnyAnnotationParameters(AnnotationNode an, String... keys) {
if (an != null && an.values != null) {
for (int i = 0; i < an.values.size(); i += 2) {
for (String key : keys) {
if (an.values.get(i).equals(key)) {
return true;
}
}
}
}
return false;
}
/**
* Check whether annotation has all the specified parameters
* @param an annotation to check
* @param keys name of parameters
* @return yes or no
*/
public static boolean hasAllAnnotationParameters(AnnotationNode an, String... keys) {
if (an != null && an.values != null) {
for (String key : keys) {
boolean found = false;
for (int i = 0; i < an.values.size(); i += 2) {
if (an.values.get(i).equals(key)) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
return false;
}
/**
* Remove specified parameter from annotation
* @param an annotation node
* @param keys name of parameters to remove
* @return true - success, false - not found
*/
public static boolean removeAnnotationParameters(AnnotationNode an, String... keys) {
if (an.values == null) {
return false;
}
for (String key : keys) {
for (int i = 0; i < an.values.size(); i += 2) {
if (an.values.get(i).equals(key)) {
an.values.remove(i + 1);
an.values.remove(i);
break;
}
}
}
return false;
}
/**
* Get specified annotation node from specified class, or null if the annotation not exist
* @param cn class to explore
* @param annotation name of annotation to look for
* @return the annotation instance or null
*/
public static AnnotationNode getClassAnnotation(ClassNode cn, String annotation) {
if (cn != null && cn.visibleAnnotations != null) {
for (AnnotationNode an : cn.visibleAnnotations) {
if (ClassUtil.toByteCodeClassName(annotation).equals(an.desc)) {
return an;
}
}
}
return null;
}
}

View File

@@ -1,7 +1,6 @@
package com.alibaba.testable.agent.util;
import com.alibaba.testable.agent.constant.ByteCodeConst;
import com.alibaba.testable.agent.constant.ConstPool;
import com.alibaba.testable.agent.tool.ImmutablePair;
import com.alibaba.testable.core.util.LogUtil;
import org.objectweb.asm.tree.*;
@@ -11,8 +10,8 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static com.alibaba.testable.agent.constant.ConstPool.FIELD_VALUE;
import static com.alibaba.testable.agent.constant.ConstPool.PROPERTY_USER_DIR;
import static com.alibaba.testable.agent.constant.ByteCodeConst.*;
import static com.alibaba.testable.agent.constant.ConstPool.*;
import static com.alibaba.testable.core.constant.ConstPool.*;
import static com.alibaba.testable.core.util.PathUtil.createFolder;
import static org.objectweb.asm.Opcodes.*;
@@ -189,7 +188,21 @@ public class BytecodeUtil {
}};
/**
* Get stack impact of a specified ops code
* java primitive type name to bytecode mapping
*/
public static Map<String, String> PRIMITIVE_TYPE_NAME_MAP = new HashMap<String, String>() {{
put("byte", String.valueOf((char)TYPE_BYTE));
put("char", String.valueOf((char)TYPE_CHAR));
put("double", String.valueOf((char)TYPE_DOUBLE));
put("float", String.valueOf((char)TYPE_FLOAT));
put("int", String.valueOf((char)TYPE_INT));
put("long", String.valueOf((char)TYPE_LONG));
put("short", String.valueOf((char)TYPE_SHORT));
put("boolean", String.valueOf((char)TYPE_BOOL));
}};
/**
* get stack impact of a specified ops code
* @param bytecode ops code to check
* @return stack change
*/
@@ -198,7 +211,7 @@ public class BytecodeUtil {
}
/**
* Make sure method has public access
* make sure method has public access
* @param access original access mark
* @return access mark with public flag
*/
@@ -210,7 +223,7 @@ public class BytecodeUtil {
}
/**
* Dump byte code to specified class file
* dump byte code to specified class file
* @param cn original class node
* @param dumpPath folder to store class file
* @param bytes original class bytes
@@ -283,15 +296,12 @@ public class BytecodeUtil {
}
private static String getDumpPathByAnnotation(ClassNode cn) {
if (cn.visibleAnnotations != null) {
for (AnnotationNode an : cn.visibleAnnotations) {
if ((ClassUtil.toByteCodeClassName(ConstPool.DUMP_TO)).equals(an.desc)) {
String path = AnnotationUtil.getAnnotationParameter(an, FIELD_VALUE, null, String.class);
String fullPath = PathUtil.join(System.getProperty(PROPERTY_USER_DIR), path);
if (createFolder(fullPath)) {
return fullPath;
}
}
AnnotationNode an = AnnotationUtil.getClassAnnotation(cn, DUMP_TO);
if (an != null) {
String path = AnnotationUtil.getAnnotationParameter(an, FIELD_VALUE, null, String.class);
String fullPath = PathUtil.join(System.getProperty(PROPERTY_USER_DIR), path);
if (createFolder(fullPath)) {
return fullPath;
}
}
return null;

View File

@@ -5,6 +5,7 @@ import com.alibaba.testable.agent.tool.ImmutablePair;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.HashMap;
import java.util.Map;
@@ -199,7 +200,7 @@ public class ClassUtil {
}
/**
* Convert byte code class name to slash separated human readable name
* Convert byte code class name to slash separated human-readable name
* @param className original name
* @return converted name
*/
@@ -208,7 +209,7 @@ public class ClassUtil {
}
/**
* Convert byte code class name to dot separated human readable name
* Convert byte code class name to dot separated human-readable name
* @param className original name
* @return converted name
*/
@@ -239,10 +240,25 @@ public class ClassUtil {
* @return outer class name
*/
public static String toOuterClassName(String name) {
int pos = name.lastIndexOf("$");
int pos = name.lastIndexOf(DOLLAR);
return (pos > 0) ? name.substring(0, pos) : name;
}
/**
* Check whether class already has a method with same signature
* @param cn class to check
* @param mn method to find
* @return exist or not
*/
public static boolean hasMethod(ClassNode cn, MethodNode mn) {
for (MethodNode m : cn.methods) {
if (m.name.equals(mn.name) && m.desc.equals(mn.desc)) {
return true;
}
}
return false;
}
private static String toDescriptor(Byte type, String objectType) {
return "(" + (char)type.byteValue() + ")L" + objectType + ";";
}

View File

@@ -1,39 +0,0 @@
package com.alibaba.testable.agent.util;
import java.util.*;
/**
* @author flin
*/
public class CollectionUtil {
/**
* Check two collection has any equaled item
* @param collectionLeft the first collection
* @param collectionRight the second collection
* @return found or not
*/
public static boolean containsAny(Collection<?> collectionLeft, Collection<?> collectionRight) {
for (Object o : collectionLeft) {
for (Object i : collectionRight) {
if (o.equals(i)) {
return true;
}
}
}
return false;
}
/**
* Generate a list of item
* @param items elements to add
* @param <T> type of element
* @return a ArrayList of provided elements
*/
public static <T> List<T> listOf(T... items) {
List<T> list = new ArrayList<T>(items.length);
Collections.addAll(list, items);
return list;
}
}

View File

@@ -6,16 +6,14 @@ import com.alibaba.testable.core.util.LogUtil;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import static com.alibaba.testable.agent.constant.ConstPool.MOCK_DIAGNOSE;
public class DiagnoseUtil {
public static void setupByClass(ClassNode cn) {
if (cn == null || cn.visibleAnnotations == null) {
return;
}
for (AnnotationNode an : cn.visibleAnnotations) {
if (ClassUtil.toByteCodeClassName(ConstPool.MOCK_DIAGNOSE).equals(an.desc)) {
setupDiagnose(an, ConstPool.FIELD_VALUE);
}
AnnotationNode an = AnnotationUtil.getClassAnnotation(cn, MOCK_DIAGNOSE);
if (an != null) {
setupDiagnose(an, ConstPool.FIELD_VALUE);
}
}

View File

@@ -6,10 +6,7 @@ import com.alibaba.testable.core.util.LogUtil;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import static com.alibaba.testable.agent.constant.ConstPool.PROPERTY_TEMP_DIR;
import static com.alibaba.testable.agent.constant.ConstPool.PROPERTY_USER_DIR;
@@ -114,7 +111,7 @@ public class GlobalConfig {
public static void addMockPackageMapping(String originPkg, String mockClassPkg) {
if (mockPkgMapping == null) {
mockPkgMapping = new HashMap<String, String>(5);
mockPkgMapping = new LinkedHashMap<String, String>(5);
}
mockPkgMapping.put(originPkg + DOT, mockClassPkg + DOT);
}

View File

@@ -0,0 +1,27 @@
package com.alibaba.testable.agent.util;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import static com.alibaba.testable.agent.constant.ConstPool.FIELD_TARGET_CLASS;
import static com.alibaba.testable.agent.constant.ConstPool.FIELD_TARGET_CLASS_NAME;
public class MockInvokeUtil {
public static String getTargetClassName(AnnotationNode an) {
Type targetClass = AnnotationUtil.getAnnotationParameter(an, FIELD_TARGET_CLASS, null, Type.class);
if (targetClass != null) {
return targetClass.getClassName();
}
return AnnotationUtil.getAnnotationParameter(an, FIELD_TARGET_CLASS_NAME, null, String.class);
}
public static boolean hasTargetClassParameter(AnnotationNode an) {
return AnnotationUtil.hasAnyAnnotationParameters(an, FIELD_TARGET_CLASS, FIELD_TARGET_CLASS_NAME);
}
public static boolean hasDuplicatedTargetClass(AnnotationNode an) {
return AnnotationUtil.hasAllAnnotationParameters(an, FIELD_TARGET_CLASS, FIELD_TARGET_CLASS_NAME);
}
}

View File

@@ -1,22 +0,0 @@
package com.alibaba.testable.agent.util;
/**
* @author flin
*/
public class StringUtil {
/**
* repeat a text many times
* @param text content to repeat
* @param times count of repeating
* @return joined string
*/
public static String repeat(String text, int times) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++) {
sb.append(text);
}
return sb.toString();
}
}

View File

@@ -3,7 +3,7 @@ package com.alibaba.testable.agent.util;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.tree.AnnotationNode;
import static com.alibaba.testable.agent.util.CollectionUtil.listOf;
import static com.alibaba.testable.core.util.CollectionUtil.fastListOf;
import static org.junit.jupiter.api.Assertions.*;
class AnnotationUtilTest {
@@ -11,7 +11,7 @@ class AnnotationUtilTest {
@Test
void should_get_annotation_parameter() {
AnnotationNode an = new AnnotationNode("");
an.values = listOf((Object)"testKey", "testValue", "demoKey", "demoValue");
an.values = fastListOf((Object)"testKey", "testValue", "demoKey", "demoValue");
assertEquals("testValue", AnnotationUtil.getAnnotationParameter(an, "testKey", "none", String.class));
assertEquals("demoValue", AnnotationUtil.getAnnotationParameter(an, "demoKey", "none", String.class));
assertEquals("none", AnnotationUtil.getAnnotationParameter(an, "testValue", "none", String.class));

View File

@@ -1,19 +0,0 @@
package com.alibaba.testable.agent.util;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CollectionUtilTest {
@Test
void should_check_collection_contains_any_element() {
assertTrue(CollectionUtil.containsAny(
CollectionUtil.listOf("a", "b"), CollectionUtil.listOf("b", "c")
));
assertFalse(CollectionUtil.containsAny(
CollectionUtil.listOf("a", "b"), CollectionUtil.listOf("c", "d")
));
}
}

View File

@@ -6,7 +6,7 @@
<parent>
<groupId>com.alibaba.testable</groupId>
<artifactId>testable-parent</artifactId>
<version>0.7.2</version>
<version>0.7.9</version>
<relativePath>../testable-parent</relativePath>
</parent>
<artifactId>testable-all</artifactId>
@@ -59,6 +59,9 @@
<goals>
<goal>jar</goal>
</goals>
<configuration>
<additionalOptions>-Xdoclint:none</additionalOptions>
</configuration>
</execution>
</executions>
</plugin>
@@ -73,6 +76,13 @@
<goals>
<goal>sign</goal>
</goals>
<configuration>
<!-- Prevent `gpg` from using pinentry programs -->
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
</configuration>
</execution>
</executions>
</plugin>

View File

@@ -6,7 +6,7 @@
<parent>
<groupId>com.alibaba.testable</groupId>
<artifactId>testable-parent</artifactId>
<version>0.7.2</version>
<version>0.7.9</version>
<relativePath>../testable-parent</relativePath>
</parent>
<artifactId>testable-core</artifactId>
@@ -14,8 +14,8 @@
<name>testable-core</name>
<properties>
<junit.version>5.6.2</junit.version>
<transmittable.thread.local.version>2.12.1</transmittable.thread.local.version>
<junit.version>5.9.1</junit.version>
<transmittable.thread.local.version>2.14.2</transmittable.thread.local.version>
</properties>
<dependencies>
@@ -80,6 +80,9 @@
<goals>
<goal>jar</goal>
</goals>
<configuration>
<additionalOptions>-Xdoclint:none</additionalOptions>
</configuration>
</execution>
</executions>
</plugin>
@@ -94,6 +97,13 @@
<goals>
<goal>sign</goal>
</goals>
<configuration>
<!-- Prevent `gpg` from using pinentry programs -->
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
</configuration>
</execution>
</executions>
</plugin>

View File

@@ -0,0 +1,22 @@
package com.alibaba.testable.core.annotation;
import javax.lang.model.type.NullType;
import java.lang.annotation.*;
/**
* Mark specified class as mock container, and allow it to inherit mock methods from other classes
*
* @author flin
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface MockContainer {
/**
* specify the classes to inherit methods from
* @return list of class
*/
Class<?>[] inherits() default NullType.class;
}

View File

@@ -27,6 +27,12 @@ public @interface MockInvoke {
*/
Class<?> targetClass() default NullType.class;
/**
* alternative to 'targetClass' field for private internal class
* @return target class full name
*/
String targetClassName() default "";
/**
* specify the effective scope of the mock method
* @return global or associated

View File

@@ -0,0 +1,10 @@
package com.alibaba.testable.core.compile;
public class CompilationException extends RuntimeException {
private static final long serialVersionUID = 5272588827551900536L;
public CompilationException(String msg) {
super(msg);
}
}

View File

@@ -0,0 +1,33 @@
package com.alibaba.testable.core.compile;
import javax.tools.SimpleJavaFileObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
/**
* Created by trung on 5/3/15.
*/
public class CompiledCode extends SimpleJavaFileObject {
private ByteArrayOutputStream baos = new ByteArrayOutputStream();
private String className;
public CompiledCode(String className) throws Exception {
super(new URI(className), Kind.CLASS);
this.className = className;
}
public String getClassName() {
return className;
}
@Override
public OutputStream openOutputStream() throws IOException {
return baos;
}
public byte[] getByteCode() {
return baos.toByteArray();
}
}

View File

@@ -0,0 +1,27 @@
package com.alibaba.testable.core.compile;
import java.util.HashMap;
import java.util.Map;
public class DynamicClassLoader extends ClassLoader {
private Map<String, CompiledCode> customCompiledCode = new HashMap<String, CompiledCode>();
public DynamicClassLoader(ClassLoader parent) {
super(parent);
}
public void addCode(CompiledCode cc) {
customCompiledCode.put(cc.getName(), cc);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
CompiledCode cc = customCompiledCode.get(name);
if (cc == null) {
return super.findClass(name);
}
byte[] byteCode = cc.getByteCode();
return defineClass(name, byteCode, 0, byteCode.length);
}
}

View File

@@ -0,0 +1,56 @@
package com.alibaba.testable.core.compile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
/**
* Created by trung on 5/3/15. Edited by turpid-monkey on 9/25/15, completed
* support for multiple compile units.
*/
public class ExtendedStandardJavaFileManager extends
ForwardingJavaFileManager<JavaFileManager> {
private List<CompiledCode> compiledCode = new ArrayList<CompiledCode>();
private DynamicClassLoader cl;
/**
* Creates a new instance of ForwardingJavaFileManager.
*
* @param fileManager
* delegate to this file manager
* @param cl
*/
protected ExtendedStandardJavaFileManager(JavaFileManager fileManager,
DynamicClassLoader cl) {
super(fileManager);
this.cl = cl;
}
@Override
public JavaFileObject getJavaFileForOutput(
JavaFileManager.Location location, String className,
JavaFileObject.Kind kind, FileObject sibling) throws IOException {
try {
CompiledCode innerClass = new CompiledCode(className);
compiledCode.add(innerClass);
cl.addCode(innerClass);
return innerClass;
} catch (Exception e) {
throw new RuntimeException(
"Error while creating in-memory output file for "
+ className, e);
}
}
@Override
public ClassLoader getClassLoader(JavaFileManager.Location location) {
return cl;
}
}

View File

@@ -0,0 +1,140 @@
package com.alibaba.testable.core.compile;
import java.util.*;
import javax.tools.*;
/**
* Compile Java sources in-memory
*/
public class InMemoryJavaCompiler {
private JavaCompiler javac;
private DynamicClassLoader classLoader;
private Iterable<String> options;
boolean ignoreWarnings = false;
private Map<String, SourceCode> sourceCodes = new HashMap<String, SourceCode>();
public static InMemoryJavaCompiler newInstance() {
return new InMemoryJavaCompiler();
}
private InMemoryJavaCompiler() {
this.javac = ToolProvider.getSystemJavaCompiler();
this.classLoader = new DynamicClassLoader(ClassLoader.getSystemClassLoader());
}
public InMemoryJavaCompiler useParentClassLoader(ClassLoader parent) {
this.classLoader = new DynamicClassLoader(parent);
return this;
}
/**
* @return the class loader used internally by the compiler
*/
public ClassLoader getClassloader() {
return classLoader;
}
/**
* Options used by the compiler, e.g. '-Xlint:unchecked'.
*
* @param options
* @return
*/
public InMemoryJavaCompiler useOptions(String... options) {
this.options = Arrays.asList(options);
return this;
}
/**
* Ignore non-critical compiler output, like unchecked/unsafe operation
* warnings.
*
* @return
*/
public InMemoryJavaCompiler ignoreWarnings() {
ignoreWarnings = true;
return this;
}
/**
* Compile all sources
*
* @return Map containing instances of all compiled classes
* @throws Exception
*/
public Map<String, Class<?>> compileAll() throws Exception {
if (sourceCodes.size() == 0) {
throw new CompilationException("No source code to compile");
}
Collection<SourceCode> compilationUnits = sourceCodes.values();
CompiledCode[] code = new CompiledCode[compilationUnits.size()];
Iterator<SourceCode> iter = compilationUnits.iterator();
for (int i = 0; i < code.length; i++) {
code[i] = new CompiledCode(iter.next().getClassName());
}
DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>();
ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager(javac.getStandardFileManager(null, null, null), classLoader);
JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, collector, options, null, compilationUnits);
boolean result = task.call();
if (!result || collector.getDiagnostics().size() > 0) {
StringBuilder exceptionMsg = new StringBuilder();
exceptionMsg.append("Unable to compile the source");
boolean hasWarnings = false;
boolean hasErrors = false;
for (Diagnostic<? extends JavaFileObject> d : collector.getDiagnostics()) {
switch (d.getKind()) {
case NOTE:
case MANDATORY_WARNING:
case WARNING:
hasWarnings = true;
break;
case OTHER:
case ERROR:
default:
hasErrors = true;
break;
}
exceptionMsg.append("\n").append("[kind=").append(d.getKind());
exceptionMsg.append(", ").append("line=").append(d.getLineNumber());
exceptionMsg.append(", ").append("message=").append(d.getMessage(Locale.US)).append("]");
}
if (hasWarnings && !ignoreWarnings || hasErrors) {
throw new CompilationException(exceptionMsg.toString());
}
}
Map<String, Class<?>> classes = new HashMap<String, Class<?>>();
for (String className : sourceCodes.keySet()) {
classes.put(className, classLoader.loadClass(className));
}
return classes;
}
/**
* Compile single source
*
* @param className
* @param sourceCode
* @return
* @throws Exception
*/
public Class<?> compile(String className, String sourceCode) throws Exception {
return addSource(className, sourceCode).compileAll().get(className);
}
/**
* Add source code to the compiler
*
* @param className
* @param sourceCode
* @return
* @throws Exception
* @see {@link #compileAll()}
*/
public InMemoryJavaCompiler addSource(String className, String sourceCode) throws Exception {
sourceCodes.put(className, new SourceCode(className, sourceCode));
return this;
}
}

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,9 @@
This part of code is under [Apache License Version 2.0](LICENSE), modified from [InMemoryJavaCompiler](https://github.com/trung/InMemoryJavaCompiler) with modification (e.g. dropping unnecessary dependence and avoid throwing raw Exception).
Many thanks to the origin author and contributors of this lovely library:
- [trung](https://github.com/trung)
- [turpid-monkey](https://github.com/turpid-monkey)
- [PKeidel](https://github.com/PKeidel)
- [fossabot](https://github.com/fossabot)
- [KOLANICH](https://github.com/KOLANICH)
- [hammadirshad](https://github.com/hammadirshad)

View File

@@ -0,0 +1,28 @@
package com.alibaba.testable.core.compile;
import javax.tools.SimpleJavaFileObject;
import java.net.URI;
/**
* Created by trung on 5/3/15.
*/
public class SourceCode extends SimpleJavaFileObject {
private final String contents;
private final String className;
public SourceCode(String className, String contents) {
super(URI.create("string:///" + className.replace('.', '/')
+ Kind.SOURCE.extension), Kind.SOURCE);
this.contents = contents;
this.className = className;
}
public String getClassName() {
return className;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return contents;
}
}

View File

@@ -6,6 +6,7 @@ import com.alibaba.testable.core.util.MockContextUtil;
import com.alibaba.testable.core.util.TestableUtil;
import java.security.InvalidParameterException;
import java.util.Arrays;
import java.util.List;
/**
@@ -145,9 +146,13 @@ public class InvocationVerifier {
}
private boolean matches(Object expectValue, Object realValue) {
return expectValue instanceof InvocationMatcher ?
((InvocationMatcher) expectValue).matchFunction.check(realValue) :
expectValue.equals(realValue);
if (expectValue instanceof InvocationMatcher) {
return ((InvocationMatcher) expectValue).matchFunction.check(realValue);
} else if (expectValue.getClass().isArray() && realValue.getClass().isArray()) {
return Arrays.deepEquals((Object[])expectValue, (Object[])realValue);
} else {
return expectValue.equals(realValue);
}
}
private String desc(Object[] args) {

View File

@@ -12,6 +12,18 @@ public enum ConstructionOption {
* 不初始化接口和抽象类型的成员
* allow members of interface or abstract class type be initialized as null
*/
EXCEPT_INTERFACE
EXCEPT_INTERFACE,
/**
* 生成的接口成员方法不返回初始化过的对象
* allow return value of methods in constructed interface be null
*/
EXCEPT_RETURN_VALUE,
/**
* 调用虚拟抽象类调用父构造方法时,不使用初始化过的参数对象
* allow to invoke constructor of abstract class with null parameter
*/
EXCEPT_CONSTRUCTOR_PARAMETER
}

View File

@@ -2,22 +2,28 @@ package com.alibaba.testable.core.model;
import com.alibaba.testable.core.util.UnnullableMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
public class MockContext {
/**
* dot separated class name
* current test class (dot separated) name
*/
public final String testClassName;
/**
* current test case name
*/
public final String testCaseName;
/**
* store of MOCK_CONTEXT.get() and MOCK_CONTEXT.set()
*/
public final Map<String, Object> parameters;
/**
* invocation record of mock method and arguments
*/
public final Map<String, List<Object[]>> invokeRecord;
public MockContext(String testClassName, String testCaseName) {

View File

@@ -0,0 +1,33 @@
package com.alibaba.testable.core.model;
import java.io.Serializable;
/**
* @author flin
*/
public class Pair<L, R> implements Serializable {
private static final long serialVersionUID = -5197546316467446976L;
/** Left object */
private L left;
/** Right object */
private R right;
public Pair(L left, R right) {
this.left = left;
this.right = right;
}
public L getLeft() {
return left;
}
public R getRight() {
return right;
}
public static <L, R> Pair<L, R> of(L l, R r) {
return new Pair<L, R>(l, r);
}
}

View File

@@ -0,0 +1,96 @@
package com.alibaba.testable.core.tool;
import java.lang.reflect.Array;
import java.util.*;
public class CollectionTool {
/**
* Get slice of args[startPos, args.length]
* @param args original item array
* @param startPos index of the first item to keep
* @return a new array with sliced items
*/
public static <T> T[] slice(T[] args, int startPos) {
return slice(args, startPos, args.length - 1);
}
/**
* Get slice of args[startPos, endPos]
* @param args original item array
* @param startPos index of the first item to keep
* @param endPos index of the last item to keep
* @return a new array with sliced items
*/
public static <T> T[] slice(T[] args, int startPos, int endPos) {
int size = endPos - startPos + 1;
if (size <= 0) {
return (T[]) Array.newInstance(args.getClass().getComponentType(), 0);
}
T[] slicedArgs = (T[])Array.newInstance(args.getClass().getComponentType(), size);
System.arraycopy(args, startPos, slicedArgs, 0, size);
return slicedArgs;
}
/**
* Create an array
* @param items elements to add
* @return array of the provided items
*/
public static <T> T[] arrayOf(T... items) {
return items;
}
/**
* Create a mutable list
* @param items elements to add
* @return list of the provided items
*/
public static <T> List<T> listOf(T... items) {
return new ArrayList<T>(Arrays.asList(items));
}
/**
* Create a mutable set
* @param items elements to add
* @return set of the provided items
*/
public static <T> Set<T> setOf(T... items) {
return new HashSet<T>(Arrays.asList(items));
}
/**
* Create a mutable map
* @param entry elements to add
* @return map of the provided items
*/
public static <K, V> Map<K, V> mapOf(Map.Entry<K, V>... entry) {
return appendMap(new HashMap<K, V>(entry.length), entry);
}
/**
* Create an mutable ordered map
* @param entry elements to add
* @return ordered map of the provided items
*/
public static <K, V> Map<K, V> orderedMapOf(Map.Entry<K, V>... entry) {
return appendMap(new LinkedHashMap<K, V>(entry.length), entry);
}
/**
* Create a map entry
* @param key the key
* @param value the value
* @return entry of provided key and value
*/
public static <K, V> Map.Entry<K, V> entryOf(K key, V value) {
return new AbstractMap.SimpleEntry<K, V>(key, value);
}
private static <K, V> Map<K, V> appendMap(Map<K, V> kvs, Map.Entry<K, V>[] entry) {
for (Map.Entry<K, V> p : entry) {
kvs.put(p.getKey(), p.getValue());
}
return kvs;
}
}

View File

@@ -139,7 +139,7 @@ public class OmniAccessor {
for (int i = 0; i < querySegments.length; i++) {
patternSegments[i] = toSinglePattern(querySegments[i]);
}
return PATTERN_PREFIX + CollectionUtil.join(Arrays.asList(patternSegments), SLASH);
return PATTERN_PREFIX + CollectionUtil.joinToString(Arrays.asList(patternSegments), SLASH);
}
private static String toSinglePattern(String querySegment) {

View File

@@ -3,13 +3,16 @@ package com.alibaba.testable.core.tool;
import com.alibaba.testable.core.exception.ClassConstructionException;
import com.alibaba.testable.core.model.ConstructionOption;
import com.alibaba.testable.core.util.CollectionUtil;
import com.alibaba.testable.core.util.ConstructionUtil;
import com.alibaba.testable.core.util.LogUtil;
import com.alibaba.testable.core.util.TypeUtil;
import java.lang.reflect.*;
import java.nio.charset.Charset;
import java.util.*;
import static com.alibaba.testable.core.constant.ConstPool.DOLLAR;
import static com.alibaba.testable.core.model.ConstructionOption.EXCEPT_INTERFACE;
import static com.alibaba.testable.core.model.ConstructionOption.EXCEPT_LOOP_NESTING;
/**
@@ -30,7 +33,7 @@ public class OmniConstructor {
* @return 返回新创建的对象
*/
public static <T> T newInstance(Class<T> clazz, ConstructionOption... options) {
T ins = newInstance(clazz, new HashSet<Class<?>>(INITIAL_CAPACITY));
T ins = newInstance(clazz, new HashSet<Class<?>>(INITIAL_CAPACITY), options);
if (ins == null || CollectionUtil.contains(options, EXCEPT_LOOP_NESTING)) {
return ins;
}
@@ -46,34 +49,38 @@ public class OmniConstructor {
* @return 返回新创建的对象数组
*/
public static <T> T[] newArray(Class<T> clazz, int size, ConstructionOption... options) {
T[] array = (T[])newArray(clazz, size, new HashSet<Class<?>>(INITIAL_CAPACITY));
T[] array = (T[])newArray(clazz, size, new HashSet<Class<?>>(INITIAL_CAPACITY), options);
if (CollectionUtil.contains(options, EXCEPT_LOOP_NESTING)) {
return array;
}
return handleCircleReference(array);
}
private static <T> T newInstance(Class<T> clazz, Set<Class<?>> classPool) {
private static <T> T newInstance(Class<T> clazz, Set<Class<?>> classPool, ConstructionOption[] options) {
LogUtil.verbose(classPool.size() * 2, "Creating %s", clazz.getName());
if (classPool.contains(clazz)) {
return null;
}
classPool.add(clazz);
T ins = createSpecialClass(clazz);
if (ins != null) {
return ins;
}
try {
if (clazz.isPrimitive()) {
return newPrimitive(clazz);
} else if (clazz.equals(Class.class)) {
return (T)Object.class;
} else if (clazz.isArray()) {
return (T)newArray(clazz.getComponentType(), 0, classPool);
return (T)newArray(clazz.getComponentType(), 0, classPool, options);
} else if (clazz.isEnum()) {
return newEnum(clazz);
} else if (clazz.isInterface()) {
return newInterface(clazz);
return newInterface(clazz, options);
} else if (Modifier.isAbstract(clazz.getModifiers())) {
return newAbstractClass(clazz);
return newAbstractClass(clazz, options);
}
return newObject(clazz, classPool);
return newObject(clazz, classPool, options);
} catch (NoSuchMethodException e) {
throw new ClassConstructionException("Failed to find constructor", e);
} catch (IllegalAccessException e) {
@@ -89,35 +96,36 @@ public class OmniConstructor {
}
}
private static <T> T newObject(Class<T> clazz, Set<Class<?>> classPool)
private static <T> T newObject(Class<T> clazz, Set<Class<?>> classPool, ConstructionOption[] options)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Object ins = createInstance(clazz, classPool);
Object ins = createInstance(clazz, classPool, options);
if (!TypeUtil.isBasicType(clazz)) {
for (Field f : TypeUtil.getAllFields(clazz)) {
f.setAccessible(true);
// skip "$jacocoData" field added by jacoco
if (f.get(ins) == null && !f.getName().startsWith(DOLLAR)) {
f.set(ins, newInstance(f.getType(), classPool));
f.set(ins, newInstance(f.getType(), classPool, options));
}
}
}
return (T)ins;
}
private static Object newArray(Class<?> clazz, int size, Set<Class<?>> classPool) {
private static Object newArray(Class<?> clazz, int size, Set<Class<?>> classPool, ConstructionOption[] options) {
// primary[] cannot be cast to Object[], have to use Object instead of T[]
Object array = Array.newInstance(clazz, size);
for (int i = 0; i < size; i++) {
Array.set(array, i, newInstance(clazz, classPool));
Array.set(array, i, newInstance(clazz, classPool, options));
}
return array;
}
private static <T> T newAbstractClass(Class<T> clazz) {
return null;
private static <T> T newAbstractClass(Class<T> clazz, ConstructionOption[] options) throws InstantiationException {
return CollectionUtil.contains(options, EXCEPT_INTERFACE) ? null
: ConstructionUtil.generateSubClassOf(clazz, options);
}
private static <T> T newInterface(Class<T> clazz) {
private static <T> T newInterface(Class<T> clazz, ConstructionOption[] options) throws InstantiationException {
if (clazz.equals(List.class)) {
return (T)Collections.emptyList();
} else if (clazz.equals(Map.class)) {
@@ -125,7 +133,7 @@ public class OmniConstructor {
} else if (clazz.equals(Set.class)) {
return (T)Collections.emptySet();
}
return null;
return newAbstractClass(clazz, options);
}
private static <T> T newEnum(Class<T> clazz)
@@ -180,7 +188,7 @@ public class OmniConstructor {
}
classPool.put(type, instance);
for (Field f : TypeUtil.getAllFields(type)) {
if (f.getName().startsWith("$") || isStaticFinalField(f)) {
if (f.getName().startsWith(DOLLAR) || isStaticFinalField(f)) {
// skip static-final fields and fields e.g. "$jacocoData"
continue;
}
@@ -225,9 +233,9 @@ public class OmniConstructor {
}
}
private static Object createInstance(Class<?> clazz, Set<Class<?>> classPool)
private static Object createInstance(Class<?> clazz, Set<Class<?>> classPool, ConstructionOption[] options)
throws InstantiationException, IllegalAccessException, InvocationTargetException {
Constructor<?> constructor = getBestConstructor(clazz);
Constructor<?> constructor = TypeUtil.getBestConstructor(clazz);
if (constructor == null) {
throw new ClassConstructionException("Fail to invoke constructor of " + clazz.getName());
}
@@ -238,29 +246,42 @@ public class OmniConstructor {
} else {
Object[] args = new Object[types.length];
for (int i = 0; i < types.length; i++) {
args[i] = types[i].equals(clazz) ? null : newInstance(types[i], classPool);
args[i] = types[i].equals(clazz) ? null : newInstance(types[i], classPool, options);
}
return constructor.newInstance(args);
}
}
private static Constructor<?> getBestConstructor(Class<?> clazz) {
Constructor<?> bestConstructor = null;
int minimalExceptionCount = 999;
int minimalParameterCount = 999;
for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
Class<?>[] parameterTypes = constructor.getParameterTypes();
Class<?>[] exceptionTypes = constructor.getExceptionTypes();
if (parameterTypes.length == 1 && parameterTypes[0].equals(Void.class)) {
return constructor;
} else if (exceptionTypes.length < minimalExceptionCount
|| (exceptionTypes.length == minimalExceptionCount && parameterTypes.length < minimalParameterCount)) {
minimalExceptionCount = exceptionTypes.length;
minimalParameterCount = parameterTypes.length;
bestConstructor = constructor;
private static <T> T createSpecialClass(Class<T> clazz) {
if (clazz.getName().equals("java.net.URL")) {
// loaded before OmniClassHandler, cannot be instrumented
try {
return clazz.getDeclaredConstructor(String.class).newInstance("https://");
} catch (Exception e) {
return null;
}
} else if (clazz.getName().equals("java.nio.charset.Charset")) {
// better to use its default instance
return (T) Charset.defaultCharset();
} else if (clazz.getName().equals("java.util.Date")) {
// better to use current time
return (T) new Date();
} else if (clazz.getName().equals("java.nio.ByteBuffer")) {
// has package-private abstract methods
try {
return (T) newInstance(Class.forName("java.nio.DirectByteBuffer"));
} catch (ClassNotFoundException e) {
return null;
}
} else if (clazz.getName().equals("java.nio.CharBuffer")) {
// has package-private abstract methods
try {
return (T) newInstance(Class.forName("java.nio.StringCharBuffer"));
} catch (ClassNotFoundException e) {
return null;
}
}
return bestConstructor;
return null;
}
}

View File

@@ -1,23 +1,18 @@
package com.alibaba.testable.core.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.*;
public class CollectionUtil {
public static Object[] slice(Object[] args, int pos) {
int size = args.length - pos;
if (size <= 0) {
return new Object[0];
}
Object[] slicedArgs = new Object[size];
System.arraycopy(args, pos, slicedArgs, 0, size);
return slicedArgs;
}
public static String join(Collection<?> collection, String joinSymbol) {
/**
* Join a collection into string
* @param collection many items with proper toString() method
* @param joinSymbol splitter of echo items
* @return a joined string
*/
public static String joinToString(Collection<?> collection, String joinSymbol) {
StringBuilder sb = new StringBuilder();
for(Iterator<?> i = collection.iterator(); i.hasNext(); sb.append((String)i.next())) {
for(Iterator<?> i = collection.iterator(); i.hasNext(); sb.append(i.next().toString())) {
if (sb.length() != 0) {
sb.append(joinSymbol);
}
@@ -25,6 +20,12 @@ public class CollectionUtil {
return sb.toString();
}
/**
* Check whether target exist in collection
* @param collection many items to find from
* @param target an item to be found
* @return whether target exist in collection
*/
public static <T> boolean contains(T[] collection, T target) {
for (T item : collection) {
if (target.equals(item)) {
@@ -33,4 +34,31 @@ public class CollectionUtil {
}
return false;
}
/**
* Check two collection has any equaled item
* @param collectionLeft the first collection
* @param collectionRight the second collection
* @return whether any equaled item found
*/
public static <T> boolean containsAny(Collection<T> collectionLeft, Collection<T> collectionRight) {
for (T left : collectionLeft) {
for (T right : collectionRight) {
if (left.equals(right)) {
return true;
}
}
}
return false;
}
/**
* Create an immutable list
* @param items elements to add
* @return list of the provided items
*/
public static <T> List<T> fastListOf(T... items) {
return Arrays.asList(items);
}
}

View File

@@ -0,0 +1,285 @@
package com.alibaba.testable.core.util;
import com.alibaba.testable.core.compile.InMemoryJavaCompiler;
import com.alibaba.testable.core.model.ConstructionOption;
import com.alibaba.testable.core.tool.OmniConstructor;
import java.lang.reflect.*;
import java.util.*;
import static com.alibaba.testable.core.constant.ConstPool.DOT;
import static com.alibaba.testable.core.model.ConstructionOption.EXCEPT_CONSTRUCTOR_PARAMETER;
import static com.alibaba.testable.core.model.ConstructionOption.EXCEPT_RETURN_VALUE;
import static com.alibaba.testable.core.tool.CollectionTool.entryOf;
import static com.alibaba.testable.core.tool.CollectionTool.mapOf;
public class ConstructionUtil {
private static final String TESTABLE_IMPL = "$TestableImpl";
/**
* Default value of basic and special types
*/
private static final Map<String, String> DEFAULT_VALUES = mapOf(
entryOf("java.lang.String", "\"mock\""),
entryOf("byte", "'\0'"),
entryOf("java.lang.Byte", "'\0'"),
entryOf("char", "'\0'"),
entryOf("java.lang.Character", "'\0'"),
entryOf("double", "1.0D"),
entryOf("java.lang.Double", "1.0D"),
entryOf("float", "1.0F"),
entryOf("java.lang.Float", "1.0F"),
entryOf("int", "1"),
entryOf("java.lang.Integer", "1"),
entryOf("short", "1"),
entryOf("java.lang.Short", "1"),
entryOf("long", "1L"),
entryOf("java.lang.Long", "1L"),
entryOf("boolean", "true"),
entryOf("java.lang.Boolean", "true"),
entryOf("java.nio.charset.Charset", "java.nio.charset.Charset.defaultCharset()")
);
public static <T> T generateSubClassOf(Class<T> clazz, ConstructionOption[] options) throws InstantiationException {
StringBuilder sourceCode = new StringBuilder();
String packageName = adaptName(clazz.getPackage().getName());
String subclassName = getSubclassName(clazz);
Map<String, String> noMapping = new HashMap<String, String>();
sourceCode.append("package ")
.append(packageName)
.append(";\npublic class ")
.append(subclassName)
.append(getTypeParameters(clazz.getTypeParameters(), true, noMapping))
.append(clazz.isInterface() ? " implements " : " extends ")
.append(getClassName(clazz, noMapping))
.append(getTypeParameters(clazz.getTypeParameters(), false, noMapping))
.append(" {\n");
sourceCode.append("\tpublic ").append(subclassName).append("() { ")
.append(invokeConstructorOf(clazz, noMapping, options)).append(" }\n");
for (String method : generateMethodsOf(clazz, new HashSet<String>(), noMapping, options)) {
sourceCode.append(method);
}
sourceCode.append("}");
try {
return (T) InMemoryJavaCompiler.newInstance()
.useParentClassLoader(clazz.getClassLoader())
.useOptions("-Xlint:unchecked")
.ignoreWarnings()
.compile(packageName + DOT + subclassName, sourceCode.toString())
.newInstance();
} catch (Throwable e) {
throw new InstantiationException(e.toString());
}
}
private static String invokeConstructorOf(Class<?> clazz, Map<String, String> genericTypes,
ConstructionOption[] options) {
if (clazz.isInterface()) {
return "";
}
Constructor<?> constructor = TypeUtil.getBestConstructor(clazz, false);
StringBuilder invocation = new StringBuilder("super(");
Type[] genericParameterTypes = constructor.getGenericParameterTypes();
Class<?>[] parameterTypes = constructor.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++) {
if (i > 0) {
invocation.append(", ");
}
invocation.append(getDefaultValue(getClassName(genericParameterTypes[i], genericTypes),
getClassName(parameterTypes[i]),
CollectionUtil.contains(options, EXCEPT_CONSTRUCTOR_PARAMETER), genericTypes));
}
invocation.append(");");
return invocation.toString();
}
private static Set<String> generateMethodsOf(Class<?> clazz, Set<String> methodPool,
Map<String, String> genericTypes, ConstructionOption[] options) {
Set<String> methods = new HashSet<String>();
// in a very special situation, getDeclaredMethods() could fetch method declaration in the parent interface
// as none-abstract, that will cause the corresponding abstract method in current class be skipped.
// it happens to e.g. CharSequence.subSequence(int,int) and CharBuffer.subSequence(int,int)
// so we would pass the methods to pool after all method in current level have been handled.
Set<String> thisLevelMethodPool = new HashSet<String>();
for (Method m : clazz.getDeclaredMethods()) {
StringBuilder methodSignatureBuilder = new StringBuilder(m.getName());
for (Type p : m.getGenericParameterTypes()) {
methodSignatureBuilder.append("#").append(getParameterName(p, genericTypes));
}
String methodSignature = methodSignatureBuilder.toString();
if (methodPool.contains(methodSignature)) {
continue;
}
thisLevelMethodPool.add(methodSignature);
if (Modifier.isAbstract(m.getModifiers())) {
StringBuilder sourceCode = new StringBuilder();
sourceCode.append("\tpublic ")
.append(getTypeParameters(m.getTypeParameters(), true, genericTypes))
.append(getClassName(m.getGenericReturnType(), genericTypes))
.append(" ").append(m.getName()).append("(");
Type[] parameters = m.getGenericParameterTypes();
for (int i = 0; i < parameters.length; i++) {
sourceCode.append(getParameterName(parameters[i], genericTypes)).append(" p").append(i);
if (i < parameters.length - 1) {
sourceCode.append(", ");
}
}
sourceCode.append(") {\n");
String returnType = getClassName(m.getGenericReturnType(), genericTypes);
if (!"void".equals(returnType)) {
sourceCode.append("\t\treturn ")
.append(getDefaultValue(returnType, getClassName(m.getReturnType()),
CollectionUtil.contains(options, EXCEPT_RETURN_VALUE), genericTypes))
.append(";\n");
}
sourceCode.append("\t}\n");
methods.add(sourceCode.toString());
}
}
methodPool.addAll(thisLevelMethodPool);
List<Type> superTypes = new ArrayList<Type>(Arrays.asList(clazz.getGenericInterfaces()));
if (clazz.getGenericSuperclass() != null) {
superTypes.add(clazz.getGenericSuperclass());
}
for (Type t : superTypes) {
if (t instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) t;
methods.addAll(generateMethodsOf((Class<?>) pt.getRawType(), methodPool, parseGenericTypes(pt), options));
} else if (t instanceof Class) {
methods.addAll(generateMethodsOf((Class<?>) t, methodPool, Collections.<String, String>emptyMap(), options));
}
}
return methods;
}
private static String getDefaultValue(String genericTypeName, String simpleTypeName, boolean alwaysUseNullParameter,
Map<String, String> genericTypes) {
if (DEFAULT_VALUES.containsKey(genericTypeName)) {
return DEFAULT_VALUES.get(genericTypeName);
} else if (genericTypeName.startsWith("java.") || alwaysUseNullParameter) {
return "null";
} else {
return "(" + genericTypeName + ") " + getClassName(OmniConstructor.class, genericTypes) +
".newInstance(" + simpleTypeName + ".class)";
}
}
private static Map<String, String> parseGenericTypes(ParameterizedType type) {
Map<String, String> templateTypeMap = new HashMap<String, String>();
Type[] actualTypeArguments = type.getActualTypeArguments();
TypeVariable<? extends Class<?>>[] rawTypedParameters = ((Class<?>) type.getRawType()).getTypeParameters();
for (int i = 0; i < actualTypeArguments.length; i++) {
templateTypeMap.put(getClassName(rawTypedParameters[i]), getClassName(actualTypeArguments[i]));
}
return templateTypeMap;
}
private static String adaptName(String name) {
// create class in 'java' package will cause 'prohibited package name' error
return name.replaceAll("^java\\.", "testable.");
}
private static String getTypeParameters(TypeVariable<?>[] typeParameters, boolean withScope,
Map<String, String> genericTypes) {
if (typeParameters.length > 0) {
StringBuilder sb = new StringBuilder("<");
for (int i = 0; i < typeParameters.length; i++) {
sb.append(typeParameters[i].getName());
if (withScope) {
sb.append(" extends ");
Type[] bounds = typeParameters[i].getBounds();
for (int j = 0; j < bounds.length; j++) {
sb.append(getClassName(bounds[j], genericTypes));
if (j < bounds.length - 1) {
sb.append(" & ");
}
}
}
if (i < typeParameters.length - 1) {
sb.append(", ");
}
}
sb.append("> ");
return sb.toString();
}
return "";
}
private static String getTypeParameters(Type[] typeParameters, Map<String, String> genericTypes) {
if (typeParameters.length > 0) {
StringBuilder sb = new StringBuilder("<");
for (int i = 0; i < typeParameters.length; i++) {
sb.append(getClassName(typeParameters[i], genericTypes));
if (i < typeParameters.length - 1) {
sb.append(", ");
}
}
sb.append("> ");
return sb.toString();
}
return "";
}
private static String getWildcardType(WildcardType wildcardType, Map<String, String> genericTypes) {
StringBuilder sb = new StringBuilder();
Type[] lowerBounds = wildcardType.getLowerBounds();
Type[] bounds = lowerBounds;
if (lowerBounds.length > 0) {
sb.append("? super ");
} else {
Type[] upperBounds = wildcardType.getUpperBounds();
if (upperBounds.length == 0 || upperBounds[0].equals(Object.class)) {
return "?";
}
bounds = upperBounds;
sb.append("? extends ");
}
boolean firstItem = true;
for (Type type : bounds) {
if (!firstItem) {
sb.append(" & ");
}
firstItem = false;
sb.append(getClassName(type, genericTypes));
}
return sb.toString();
}
private static String getClassName(Type clazz) {
return (clazz instanceof Class) ? ((Class<?>)clazz).getCanonicalName() : clazz.toString();
}
private static String getClassName(Type clazz, Map<String, String> genericTypes) {
if (clazz instanceof Class) {
return ((Class<?>)clazz).getCanonicalName();
} else if (clazz instanceof GenericArrayType) {
return getClassName(((GenericArrayType) clazz).getGenericComponentType(), genericTypes) + "[]";
} else if (clazz instanceof TypeVariable) {
String name = ((TypeVariable<?>)clazz).getName();
return genericTypes.containsKey(name) ? genericTypes.get(name) : name;
} else if (clazz instanceof ParameterizedType) {
ParameterizedType ptClazz = (ParameterizedType)clazz;
return getClassName(ptClazz.getRawType()) + getTypeParameters(ptClazz.getActualTypeArguments(), genericTypes);
} else if (clazz instanceof WildcardType) {
return getWildcardType((WildcardType)clazz, genericTypes);
}
return clazz.toString();
}
private static String getParameterName(Type parameter, Map<String, String> genericTypes) {
if (parameter instanceof Class && ((Class<?>)parameter).isArray()) {
return getParameterName(((Class<?>)parameter).getComponentType(), genericTypes) + "[]";
}
return getClassName(parameter, genericTypes);
}
private static String getSubclassName(Class<?> clazz) {
return clazz.getSimpleName() + TESTABLE_IMPL;
}
}

View File

@@ -1,6 +1,7 @@
package com.alibaba.testable.core.util;
import com.alibaba.testable.core.model.MockContext;
import com.alibaba.testable.core.tool.CollectionTool;
/**
* @author flin
@@ -31,7 +32,7 @@ public class InvokeRecordUtil {
mockContext.invokeRecord.get(mockMethodName).add(args);
LogUtil.verbose(" Mock constructor \"%s\" invoked in %s::%s", mockMethodName, testClass, testCaseName);
} else {
mockContext.invokeRecord.get(mockMethodName).add(CollectionUtil.slice(args, 1));
mockContext.invokeRecord.get(mockMethodName).add(CollectionTool.slice(args, 1));
LogUtil.verbose(" Mock method \"%s\" invoked in %s::%s\"", mockMethodName, testClass, testCaseName);
}
}

View File

@@ -2,6 +2,7 @@ package com.alibaba.testable.core.util;
import com.alibaba.testable.core.exception.MemberAccessException;
import com.alibaba.testable.core.model.MockContext;
import com.alibaba.testable.core.tool.CollectionTool;
import java.util.HashSet;
import java.util.Map;
@@ -71,7 +72,7 @@ public class MockAssociationUtil {
return construct(originClass, args);
} else if (args[0] == null) {
try {
return invokeStatic(originClass, originMethod, CollectionUtil.slice(args, 1));
return invokeStatic(originClass, originMethod, CollectionTool.slice(args, 1));
} catch (RuntimeException e) {
if (e instanceof MemberAccessException && e.getCause() instanceof NoSuchFieldException) {
throw new NullPointerException("Invoking method \"" + originMethod + "\" of null object");
@@ -79,7 +80,7 @@ public class MockAssociationUtil {
throw e;
}
} else {
return invoke(args[0], originMethod, CollectionUtil.slice(args, 1));
return invoke(args[0], originMethod, CollectionTool.slice(args, 1));
}
}

View File

@@ -2,12 +2,35 @@ package com.alibaba.testable.core.util;
public class StringUtil {
public static String repeat(String str, int n) {
/**
* repeat a text many times
* @param text content to repeat
* @param times count of repeating
* @return repeated string
*/
public static String repeat(String text, int times) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(str);
for (int i = 0; i < times; i++) {
sb.append(text);
}
return sb.toString();
}
/**
* concat several strings into a single string
* @param delimiter symbol to add between provided strings
* @param s an array of string to join
* @return joined string
*/
public static String join(String delimiter, String... s) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < s.length; i++) {
stringBuilder.append(s[i]);
if (i != s.length - 1) {
stringBuilder.append(delimiter);
}
}
return stringBuilder.toString();
}
}

View File

@@ -111,6 +111,42 @@ public class TypeUtil {
|| clazz.equals(Class.class) || clazz.equals(String.class);
}
/**
* find the simplest constructor for specified class
* @param clazz any class
* @return best constructor
*/
public static Constructor<?> getBestConstructor(Class<?> clazz, boolean useGeneratedConstructor) {
Constructor<?> bestConstructor = null;
int minimalExceptionCount = 999;
int minimalParameterCount = 999;
for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
Class<?>[] parameterTypes = constructor.getParameterTypes();
Class<?>[] exceptionTypes = constructor.getExceptionTypes();
if (parameterTypes.length == 1 && parameterTypes[0].equals(Void.class)) {
// if generated constructor allowed then use it, otherwise skip and continue
if (useGeneratedConstructor) {
return constructor;
}
} else if (exceptionTypes.length < minimalExceptionCount
|| (exceptionTypes.length == minimalExceptionCount && parameterTypes.length < minimalParameterCount)) {
minimalExceptionCount = exceptionTypes.length;
minimalParameterCount = parameterTypes.length;
bestConstructor = constructor;
}
}
return bestConstructor;
}
/**
* find the simplest constructor including the testable generated one
* @param clazz any class
* @return best constructor
*/
public static Constructor<?> getBestConstructor(Class<?> clazz) {
return getBestConstructor(clazz, true);
}
/**
* type equals
* @param classesLeft class to be compared

View File

@@ -0,0 +1,118 @@
package com.alibaba.testable.core.compile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class InMemoryJavaCompilerTest {
@Test
public void compile_WhenTypical() throws Exception {
final StringBuffer sourceCode = new StringBuffer();
sourceCode.append("package org.mdkt;\n");
sourceCode.append("public class HelloClass {\n");
sourceCode.append(" public String hello() { return \"hello\"; }");
sourceCode.append("}");
Class<?> helloClass = InMemoryJavaCompiler.newInstance().compile("org.mdkt.HelloClass", sourceCode.toString());
assertNotNull(helloClass);
assertEquals(1, helloClass.getDeclaredMethods().length);
}
@Test
public void compileAll_WhenTypical() throws Exception {
String cls1 = "public class A{ public B b() { return new B(); }}";
String cls2 = "public class B{ public String toString() { return \"B!\"; }}";
Map<String, Class<?>> compiled = InMemoryJavaCompiler.newInstance().addSource("A", cls1).addSource("B", cls2).compileAll();
assertNotNull(compiled.get("A"));
assertNotNull(compiled.get("B"));
Class<?> aClass = compiled.get("A");
Object a = aClass.newInstance();
assertEquals("B!", aClass.getMethod("b").invoke(a).toString());
}
@Test
public void compile_WhenSourceContainsInnerClasses() throws Exception {
final StringBuffer sourceCode = new StringBuffer();
sourceCode.append("package org.mdkt;\n");
sourceCode.append("public class HelloClass {\n");
sourceCode.append(" private static class InnerHelloWorld { int inner; }\n");
sourceCode.append(" public String hello() { return \"hello\"; }");
sourceCode.append("}");
Class<?> helloClass = InMemoryJavaCompiler.newInstance().compile("org.mdkt.HelloClass", sourceCode.toString());
assertNotNull(helloClass);
assertEquals(1, helloClass.getDeclaredMethods().length);
}
@Test
public void compile_whenError() throws Exception {
final StringBuffer sourceCode = new StringBuffer();
sourceCode.append("package org.mdkt;\n");
sourceCode.append("public classHelloClass {\n");
sourceCode.append(" public String hello() { return \"hello\"; }");
sourceCode.append("}");
assertThrows(CompilationException.class, new Executable() {
@Override
public void execute() throws Throwable {
InMemoryJavaCompiler.newInstance().compile("org.mdkt.HelloClass", sourceCode.toString());
}
}, "Unable to compile the source");
}
@Test
public void compile_WhenFailOnWarnings() throws Exception {
final StringBuffer sourceCode = new StringBuffer();
sourceCode.append("package org.mdkt;\n");
sourceCode.append("public class HelloClass {\n");
sourceCode.append(" public java.util.List<String> hello() { return new java.util.ArrayList(); }");
sourceCode.append("}");
assertThrows(CompilationException.class, new Executable() {
@Override
public void execute() throws Throwable {
InMemoryJavaCompiler.newInstance().compile("org.mdkt.HelloClass", sourceCode.toString());
}
});
}
@Test
public void compile_WhenIgnoreWarnings() throws Exception {
final StringBuffer sourceCode = new StringBuffer();
sourceCode.append("package org.mdkt;\n");
sourceCode.append("public class HelloClass {\n");
sourceCode.append(" public java.util.List<String> hello() { return new java.util.ArrayList(); }");
sourceCode.append("}");
Class<?> helloClass = InMemoryJavaCompiler.newInstance().ignoreWarnings().compile("org.mdkt.HelloClass", sourceCode.toString());
List<?> res = (List<?>) helloClass.getMethod("hello").invoke(helloClass.newInstance());
assertEquals(0, res.size());
}
@Test
public void compile_WhenWarningsAndErrors() throws Exception {
final StringBuffer sourceCode = new StringBuffer();
sourceCode.append("package org.mdkt;\n");
sourceCode.append("public class HelloClass extends xxx {\n");
sourceCode.append(" public java.util.List<String> hello() { return new java.util.ArrayList(); }");
sourceCode.append("}");
assertThrows(CompilationException.class, new Executable() {
@Override
public void execute() throws Throwable {
InMemoryJavaCompiler.newInstance().compile("org.mdkt.HelloClass", sourceCode.toString());
}
});
}
}

View File

@@ -0,0 +1,47 @@
package com.alibaba.testable.core.matcher;
import com.alibaba.testable.core.tool.OmniConstructor;
import com.alibaba.testable.core.tool.PrivateAccessor;
import org.junit.jupiter.api.Test;
import static com.alibaba.testable.core.tool.CollectionTool.listOf;
import static org.junit.jupiter.api.Assertions.*;
class InvocationVerifierTest {
private InvocationVerifier invocationVerifier = OmniConstructor.newInstance(InvocationVerifier.class);
@Test
void should_matches_object() {
assertTrue((Boolean)PrivateAccessor.invoke(invocationVerifier, "matches", "abc", "abc"));
assertTrue((Boolean)PrivateAccessor.invoke(invocationVerifier, "matches", 1L, 1L));
assertFalse((Boolean)PrivateAccessor.invoke(invocationVerifier, "matches", "xyz", "abc"));
assertFalse((Boolean)PrivateAccessor.invoke(invocationVerifier, "matches", 1L, "abc"));
assertFalse((Boolean)PrivateAccessor.invoke(invocationVerifier, "matches", 1L, 1));
}
@Test
void should_matches_array() {
assertTrue((Boolean)PrivateAccessor.invoke(invocationVerifier, "matches",
new String[] {"abc", "xyz"}, new String[] {"abc", "xyz"}));
assertFalse((Boolean)PrivateAccessor.invoke(invocationVerifier, "matches",
new String[] {"abc", "xyz"}, new String[] {"xyz", "abc"}));
assertFalse((Boolean)PrivateAccessor.invoke(invocationVerifier, "matches",
new String[] {"abc", "xyz"}, new String[] {"xyz"}));
}
@Test
void should_matches_matcher() {
assertTrue((Boolean)PrivateAccessor.invoke(invocationVerifier, "matches",
InvocationMatcher.anyArray(), new String[] {"abc", "xyz"}));
assertTrue((Boolean)PrivateAccessor.invoke(invocationVerifier, "matches",
InvocationMatcher.anyString(), "abc"));
assertFalse((Boolean)PrivateAccessor.invoke(invocationVerifier, "matches",
InvocationMatcher.anyString(), new String[] {"abc", "xyz"}));
assertFalse((Boolean)PrivateAccessor.invoke(invocationVerifier, "matches",
InvocationMatcher.anyArray(), "abc"));
}
}

View File

@@ -0,0 +1,129 @@
package com.alibaba.testable.core.tool;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.alibaba.testable.core.tool.CollectionTool.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CollectionToolTest {
@Test
void should_slice_array() {
String[] fullWords = arrayOf("this", "is", "a", "simple", "example");
String[] partOfWords = slice(fullWords, 1, 3);
assertEquals(3, partOfWords.length);
assertEquals("is", partOfWords[0]);
assertEquals("a", partOfWords[1]);
assertEquals("simple", partOfWords[2]);
Integer[] fibonacci = arrayOf(1, 1, 2, 3, 5, 8, 13, 21);
Integer[] partOfFibonacci = slice(fibonacci, 4);
assertEquals(4, partOfFibonacci.length);
assertEquals(5, partOfFibonacci[0]);
assertEquals(8, partOfFibonacci[1]);
assertEquals(13, partOfFibonacci[2]);
assertEquals(21, partOfFibonacci[3]);
}
@Test
void should_create_array() {
String[] manyWords = arrayOf("this", "is", "an", "example");
assertEquals(4, manyWords.length);
assertEquals("this", manyWords[0]);
assertEquals("is", manyWords[1]);
assertEquals("an", manyWords[2]);
assertEquals("example", manyWords[3]);
Double[] manyValues = arrayOf(1.0D, 2.0D, 3.0D);
assertEquals(3, manyValues.length);
assertEquals(1.0D, manyValues[0]);
assertEquals(2.0D, manyValues[1]);
assertEquals(3.0D, manyValues[2]);
}
@Test
void should_create_list() {
List<String> manyWords = listOf("this", "is", "an", "example");
assertEquals(4, manyWords.size());
assertEquals("this", manyWords.get(0));
assertEquals("is", manyWords.get(1));
assertEquals("an", manyWords.get(2));
assertEquals("example", manyWords.get(3));
List<Double> manyValues = listOf(1.0D, 2.0D, 3.0D);
assertEquals(3, manyValues.size());
assertEquals(1.0D, manyValues.get(0));
assertEquals(2.0D, manyValues.get(1));
assertEquals(3.0D, manyValues.get(2));
}
@Test
void should_create_set() {
Set<String> manyWords = setOf("this", "is", "an", "example");
assertEquals(4, manyWords.size());
assertTrue(manyWords.contains("this"));
assertTrue(manyWords.contains("is"));
assertTrue(manyWords.contains("an"));
assertTrue(manyWords.contains("example"));
Set<Double> manyValues = setOf(1.0D, 2.0D, 3.0D);
assertEquals(3, manyValues.size());
assertTrue(manyValues.contains(1.0D));
assertTrue(manyValues.contains(2.0D));
assertTrue(manyValues.contains(3.0D));
}
@Test
void should_create_map() {
Map<String, String> manyWords = mapOf(
entryOf("language", "java"),
entryOf("type", "unittest"),
entryOf("library", "testable")
);
assertEquals(3, manyWords.size());
assertEquals("java", manyWords.get("language"));
assertEquals("unittest", manyWords.get("type"));
assertEquals("testable", manyWords.get("library"));
Map<Integer, Double> manyValues = mapOf(
entryOf(1, 10.12D),
entryOf(2, 20.24D),
entryOf(3, 30.36D)
);
assertEquals(3, manyValues.size());
assertEquals(10.12D, manyValues.get(1));
assertEquals(20.24D, manyValues.get(2));
assertEquals(30.36D, manyValues.get(3));
}
@Test
void should_create_ordered_map() {
Map<String, String> manyWords = orderedMapOf(
entryOf("language", "java"),
entryOf("type", "unittest"),
entryOf("library", "testable")
);
assertEquals(3, manyWords.size());
String[] wordKeys = manyWords.keySet().toArray(new String[0]);
assertEquals("language", wordKeys[0]);
assertEquals("type", wordKeys[1]);
assertEquals("library", wordKeys[2]);
Map<Integer, Double> manyValues = orderedMapOf(
entryOf(1, 10.12D),
entryOf(2, 20.24D),
entryOf(3, 30.36D)
);
assertEquals(3, manyValues.size());
Integer[] valueKeys = manyValues.keySet().toArray(new Integer[0]);
assertEquals(1, valueKeys[0]);
assertEquals(2, valueKeys[1]);
assertEquals(3, valueKeys[2]);
}
}

View File

@@ -2,17 +2,19 @@ package com.alibaba.testable.core.util;
import org.junit.jupiter.api.Test;
import static com.alibaba.testable.core.tool.PrivateAccessor.invokeStatic;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.alibaba.testable.core.util.CollectionUtil.fastListOf;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CollectionUtilTest {
@Test
void should_slice_array() {
Object[] args = new Object[]{"1", "2", "3"};
Object[] slicedArgs = invokeStatic(CollectionUtil.class, "slice", args, 1);
assertEquals(2, slicedArgs.length);
assertEquals("2", slicedArgs[0]);
assertEquals("3", slicedArgs[1]);
void should_check_collection_contains_any_element() {
assertTrue(CollectionUtil.containsAny(
fastListOf("a", "b"), fastListOf("b", "c")
));
assertFalse(CollectionUtil.containsAny(
fastListOf("a", "b"), fastListOf("c", "d")
));
}
}

View File

@@ -0,0 +1,119 @@
package com.alibaba.testable.core.util;
import com.alibaba.testable.core.model.ConstructionOption;
import org.junit.jupiter.api.Test;
import sun.reflect.generics.factory.CoreReflectionFactory;
import sun.reflect.generics.reflectiveObjects.GenericArrayTypeImpl;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;
import sun.reflect.generics.reflectiveObjects.TypeVariableImpl;
import sun.reflect.generics.reflectiveObjects.WildcardTypeImpl;
import sun.reflect.generics.scope.MethodScope;
import sun.reflect.generics.tree.SimpleClassTypeSignature;
import sun.reflect.generics.tree.TypeArgument;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import static com.alibaba.testable.core.tool.PrivateAccessor.construct;
import static com.alibaba.testable.core.tool.PrivateAccessor.invokeStatic;
import static com.alibaba.testable.core.tool.CollectionTool.arrayOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class ConstructionUtilTest {
public interface EmptyInterface {}
public interface RealInterface {
void noParameterMethod();
int primaryTypeParameterMethod(double d, boolean b);
String clazzAndArrayParameterMethod(String s, byte[] b);
EmptyInterface interfaceAndSelfReferenceParameterMethod(RealInterface i, EmptyInterface[] e);
<T> T templatedParameterMethod(T i);
}
public static abstract class AbstractClazz implements RealInterface {
@Override
public void noParameterMethod() {}
public abstract <T extends String> T getByName(T name);
public abstract String getByTags(List<? extends String> tags);
public static <T> T useless() { return null; }
}
public static abstract class ParameterizedClazz<S extends String, P> extends AbstractClazz implements RealInterface, EmptyInterface {
public abstract S getById(S id);
public abstract S getByIds(List<S> ids);
public abstract P getByMap(Map<String, P> m);
}
public interface StringMap extends Map<String, Object> {
<K> K nextKey(K k);
<V> V nextValue(V v);
}
public interface Inner$Interface {}
private final ConstructionOption[] options = arrayOf();
@Test
void should_generate_empty_interface() throws Exception {
EmptyInterface ins = ConstructionUtil.generateSubClassOf(EmptyInterface.class, options);
assertNotNull(ins);
}
@Test
void should_generate_real_interface() throws Exception {
RealInterface ins = ConstructionUtil.generateSubClassOf(RealInterface.class, options);
assertNotNull(ins);
}
@Test
void should_generate_abstract_class() throws Exception {
RealInterface ins = ConstructionUtil.generateSubClassOf(AbstractClazz.class, options);
assertNotNull(ins);
}
@Test
void should_generate_parameterized_class() throws Exception {
RealInterface ins = ConstructionUtil.generateSubClassOf(ParameterizedClazz.class, options);
assertNotNull(ins);
}
@Test
void should_generate_implicit_generic_interface() throws Exception {
StringMap ins = ConstructionUtil.generateSubClassOf(StringMap.class, options);
assertNotNull(ins);
}
@Test
void should_generate_name_with_dollar() throws Exception {
Inner$Interface ins = ConstructionUtil.generateSubClassOf(Inner$Interface.class, options);
assertNotNull(ins);
}
@Test
void should_get_class_name() throws Exception {
// common class, e.g. String
assertEquals("java.lang.String",
invokeStatic(ConstructionUtil.class, "getClassName", String.class));
// array class, e.g. String[]
assertEquals("java.lang.String[]",
invokeStatic(ConstructionUtil.class, "getClassName", GenericArrayTypeImpl.make(String.class)));
// typed class, e.g. T
Method fakeMethod = construct(Method.class, String.class, "fake", new Class[0], String.class, new Class[0], Modifier.PUBLIC, 0, "", null, null, null);
assertEquals("T", invokeStatic(ConstructionUtil.class, "getClassName", TypeVariableImpl.make(
fakeMethod, "T", arrayOf(SimpleClassTypeSignature.make("java.lang.String", false, new TypeArgument[0])),
CoreReflectionFactory.make(fakeMethod, MethodScope.make(fakeMethod)))));
// wildcard class, e.g. ? extends String
assertEquals("? extends java.lang.String", invokeStatic(ConstructionUtil.class, "getClassName", WildcardTypeImpl.make(
arrayOf(SimpleClassTypeSignature.make("java.lang.String", false, new TypeArgument[0])),
new SimpleClassTypeSignature[0],
CoreReflectionFactory.make(String.class, MethodScope.make(fakeMethod)))));
// parameterized class, e.g. Map<String, Object>
assertEquals("java.util.Map<java.lang.String, java.lang.Object>",
invokeStatic(ConstructionUtil.class, "getClassName", ParameterizedTypeImpl.make(Map.class,
arrayOf(String.class, Object.class), null)));
}
}

Some files were not shown because too many files have changed in this diff Show More