Skip to content

Commit

Permalink
New module mock-beans
Browse files Browse the repository at this point in the history
Signed-off-by: Jorge Bescos Gascon <jorge.bescos.gascon@oracle.com>
  • Loading branch information
jbescos committed May 7, 2024
1 parent 8e9d040 commit c1b42fe
Show file tree
Hide file tree
Showing 20 changed files with 196 additions and 172 deletions.
4 changes: 4 additions & 0 deletions all/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -773,6 +773,10 @@
<groupId>io.helidon.messaging.mock</groupId>
<artifactId>helidon-messaging-mock</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.microprofile.testing</groupId>
<artifactId>helidon-microprofile-testing-mock-beans</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.logging</groupId>
<artifactId>helidon-logging-common</artifactId>
Expand Down
5 changes: 5 additions & 0 deletions bom/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1028,6 +1028,11 @@
<artifactId>helidon-messaging-mock</artifactId>
<version>${helidon.version}</version>
</dependency>
<dependency>
<groupId>io.helidon.microprofile.testing</groupId>
<artifactId>helidon-microprofile-testing-mock-beans</artifactId>
<version>${helidon.version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>io.helidon.logging</groupId>
Expand Down
6 changes: 6 additions & 0 deletions dependencies/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
<version.lib.animal-sniffer>1.18</version.lib.animal-sniffer>
<version.lib.annotation-api>1.3.5</version.lib.annotation-api>
<version.lib.brave-opentracing>1.0.0</version.lib.brave-opentracing>
<version.lib.bytebuddy>1.14.14</version.lib.bytebuddy>
<version.lib.commons-codec>1.16.0</version.lib.commons-codec>
<version.lib.commons-logging>1.2</version.lib.commons-logging>
<version.lib.cron-utils>9.1.6</version.lib.cron-utils>
Expand Down Expand Up @@ -501,6 +502,11 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>${version.lib.bytebuddy}</version>
</dependency>
<dependency>
<groupId>jakarta.websocket</groupId>
<artifactId>jakarta.websocket-api</artifactId>
Expand Down
6 changes: 0 additions & 6 deletions microprofile/testing/junit5/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,6 @@
<artifactId>junit-jupiter-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.helidon.jersey</groupId>
<artifactId>helidon-jersey-client</artifactId>
Expand All @@ -72,7 +67,6 @@
<artifactId>hamcrest-core</artifactId>
<scope>test</scope>
</dependency>

</dependencies>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
Expand All @@ -49,16 +48,11 @@
import jakarta.enterprise.inject.se.SeContainer;
import jakarta.enterprise.inject.se.SeContainerInitializer;
import jakarta.enterprise.inject.spi.AfterBeanDiscovery;
import jakarta.enterprise.inject.spi.AnnotatedParameter;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.inject.spi.BeforeBeanDiscovery;
import jakarta.enterprise.inject.spi.CDI;
import jakarta.enterprise.inject.spi.Extension;
import jakarta.enterprise.inject.spi.InjectionPoint;
import jakarta.enterprise.inject.spi.ProcessAnnotatedType;
import jakarta.enterprise.inject.spi.ProcessInjectionPoint;
import jakarta.enterprise.inject.spi.WithAnnotations;
import jakarta.enterprise.inject.spi.configurator.AnnotatedTypeConfigurator;
import jakarta.enterprise.util.AnnotationLiteral;
import jakarta.inject.Inject;
Expand All @@ -83,8 +77,6 @@
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import org.mockito.MockSettings;
import org.mockito.Mockito;


/**
Expand Down Expand Up @@ -302,11 +294,6 @@ private void validatePerTest() {
+ " injection into fields or constructor is not supported, as each"
+ " test method uses a different CDI container. Field " + field
+ " is annotated with @Inject");
} else if (field.getAnnotation(MockBean.class) != null) {
throw new RuntimeException("When a class is annotated with @HelidonTest(resetPerTest=true),"
+ " injection into fields or constructor is not supported, as each"
+ " test method uses a different CDI container. Field " + field
+ " is annotated with @MockBean");
}
}

Expand All @@ -317,11 +304,6 @@ private void validatePerTest() {
+ " injection into fields or constructor is not supported, as each"
+ " test method uses a different CDI container. Field " + field
+ " is annotated with @Inject");
} else if (field.getAnnotation(MockBean.class) != null) {
throw new RuntimeException("When a class is annotated with @HelidonTest(resetPerTest=true),"
+ " injection into fields or constructor is not supported, as each"
+ " test method uses a different CDI container. Field " + field
+ " is annotated with @MockBean");
}
}
}
Expand Down Expand Up @@ -548,13 +530,13 @@ private static class AddBeansExtension implements Extension {
private final List<AddBean> addBeans;

private final HashMap<String, Annotation> socketAnnotations = new HashMap<>();
private final Set<Class<?>> mocks = new HashSet<>();

private AddBeansExtension(Class<?> testClass, List<AddBean> addBeans) {
this.testClass = testClass;
this.addBeans = addBeans;
}


void processSocketInjectionPoints(@Observes ProcessInjectionPoint<?, WebTarget> event) throws Exception{
InjectionPoint injectionPoint = event.getInjectionPoint();
Set<Annotation> qualifiers = injectionPoint.getQualifiers();
Expand All @@ -565,36 +547,10 @@ void processSocketInjectionPoints(@Observes ProcessInjectionPoint<?, WebTarget>
break;
}
}
}

void processMockBean(@Observes @WithAnnotations(MockBean.class) ProcessAnnotatedType<?> obj) throws Exception {
var configurator = obj.configureAnnotatedType();
configurator.fields().forEach(field -> {
MockBean mockBean = field.getAnnotated().getAnnotation(MockBean.class);
if (mockBean != null) {
Field f = field.getAnnotated().getJavaMember();
// Adds @Inject to be more user friendly
field.add(Literal.INSTANCE);
Class<?> fieldType = f.getType();
mocks.add(fieldType);
}
});
configurator.constructors().forEach(constructor -> {
processMockBeanParameters(constructor.getAnnotated().getParameters());
});
}

private void processMockBeanParameters(List<? extends AnnotatedParameter<?>> parameters) {
parameters.stream().forEach(parameter -> {
MockBean mockBean = parameter.getAnnotation(MockBean.class);
if (mockBean != null) {
Class<?> parameterType = parameter.getJavaParameter().getType();
mocks.add(parameterType);
}
});
}

void registerOtherBeans(@Observes AfterBeanDiscovery event, BeanManager beanManager) {
void registerOtherBeans(@Observes AfterBeanDiscovery event) {

Client client = ClientBuilder.newClient();

Expand All @@ -613,25 +569,6 @@ void registerOtherBeans(@Observes AfterBeanDiscovery event, BeanManager beanMana
.scope(ApplicationScoped.class)
.createWith(context -> getWebTarget(client, "@default"));

// Register all mocks
mocks.forEach(type -> {
event.addBean()
.addType(type)
.scope(ApplicationScoped.class)
.alternative(true)
.createWith(inst -> {
Set<Bean<?>> beans = beanManager.getBeans(MockSettings.class);
if (!beans.isEmpty()) {
Bean<?> bean = beans.iterator().next();
MockSettings mockSettings = (MockSettings) beanManager.getReference(bean, MockSettings.class,
beanManager.createCreationalContext(null));
return Mockito.mock(type, mockSettings);
} else {
return Mockito.mock(type);
}
})
.priority(0);
});
}

@SuppressWarnings("unchecked")
Expand Down Expand Up @@ -830,15 +767,4 @@ public Class<? extends Extension> value() {
}
}

/**
* Supports inline instantiation of the {@link Inject} annotation.
*/
private static final class Literal extends AnnotationLiteral<Inject> implements Inject {

private static final Literal INSTANCE = new Literal();

@Serial
private static final long serialVersionUID = 1L;

}
}
1 change: 0 additions & 1 deletion microprofile/testing/junit5/src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
requires io.helidon.microprofile.cdi;
requires jakarta.inject;
requires org.junit.jupiter.api;
requires org.mockito;

requires transitive jakarta.cdi;
requires transitive jakarta.ws.rs;
Expand Down
47 changes: 47 additions & 0 deletions microprofile/testing/mock-beans/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2024 Oracle and/or its affiliates.
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.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.helidon.microprofile.testing</groupId>
<artifactId>helidon-microprofile-testing-project</artifactId>
<version>4.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

<artifactId>helidon-microprofile-testing-mock-beans</artifactId>
<name>Helidon Microprofile Testing Mock Beans</name>

<description>
Integration with Mock Beans to support tests with CDI injection
</description>

<dependencies>
<dependency>
<groupId>io.helidon.microprofile.cdi</groupId>
<artifactId>helidon-microprofile-cdi</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

package io.helidon.microprofile.testing.junit5;
package io.helidon.microprofile.testing.mockbeans;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* Copyright (c) 2024 Oracle and/or its affiliates.
*
* 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.
*/
package io.helidon.microprofile.testing.mockbeans;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.literal.InjectLiteral;
import jakarta.enterprise.inject.spi.AfterBeanDiscovery;
import jakarta.enterprise.inject.spi.AnnotatedParameter;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.inject.spi.Extension;
import jakarta.enterprise.inject.spi.ProcessAnnotatedType;
import jakarta.enterprise.inject.spi.WithAnnotations;
import org.mockito.MockSettings;
import org.mockito.Mockito;

/**
* CDI extension for Mock Beans implementation.
*/
public class MockBeansCdiExtension implements Extension {

private final Set<Class<?>> mocks = new HashSet<>();

void processMockBean(@Observes @WithAnnotations(MockBean.class) ProcessAnnotatedType<?> obj) throws Exception {
var configurator = obj.configureAnnotatedType();
configurator.fields().forEach(field -> {
MockBean mockBean = field.getAnnotated().getAnnotation(MockBean.class);
if (mockBean != null) {
Field f = field.getAnnotated().getJavaMember();
// Adds @Inject to be more user friendly
field.add(InjectLiteral.INSTANCE);
Class<?> fieldType = f.getType();
mocks.add(fieldType);
}
});
configurator.constructors().forEach(constructor -> {
processMockBeanParameters(constructor.getAnnotated().getParameters());
});
}

private void processMockBeanParameters(List<? extends AnnotatedParameter<?>> parameters) {
parameters.stream().forEach(parameter -> {
MockBean mockBean = parameter.getAnnotation(MockBean.class);
if (mockBean != null) {
Class<?> parameterType = parameter.getJavaParameter().getType();
mocks.add(parameterType);
}
});
}

void registerOtherBeans(@Observes AfterBeanDiscovery event, BeanManager beanManager) {
// Register all mocks
mocks.forEach(type -> {
event.addBean()
.addType(type)
.scope(ApplicationScoped.class)
.alternative(true)
.createWith(inst -> {
Set<Bean<?>> beans = beanManager.getBeans(MockSettings.class);
if (!beans.isEmpty()) {
Bean<?> bean = beans.iterator().next();
MockSettings mockSettings = (MockSettings) beanManager.getReference(bean, MockSettings.class,
beanManager.createCreationalContext(null));
return Mockito.mock(type, mockSettings);
} else {
return Mockito.mock(type);
}
})
.priority(0);
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Copyright (c) 2024 Oracle and/or its affiliates.
*
* 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.
*/

/**
* Helidon implementation of mock beans.
*/
package io.helidon.microprofile.testing.mockbeans;
Loading

0 comments on commit c1b42fe

Please sign in to comment.