Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,13 @@

import org.jboss.builder.BuildChain;
import org.jboss.builder.BuildChainBuilder;
import org.jboss.builder.BuildExecutionBuilder;
import org.jboss.builder.BuildResult;
import org.jboss.builder.item.BuildItem;
import org.jboss.logging.Logger;

import io.quarkus.deployment.builditem.AdditionalApplicationArchiveBuildItem;
import io.quarkus.deployment.builditem.AdditionalApplicationArchiveMarkerBuildItem;
import io.quarkus.deployment.builditem.ArchiveRootBuildItem;
import io.quarkus.deployment.builditem.ClassOutputBuildItem;
import io.quarkus.deployment.builditem.ExtensionClassLoaderBuildItem;
Expand All @@ -49,6 +52,7 @@ public class QuarkusAugmentor {
private final Set<Class<? extends BuildItem>> finalResults;
private final List<Consumer<BuildChainBuilder>> buildChainCustomizers;
private final LaunchMode launchMode;
private final List<Path> additionalApplicationArchives;

QuarkusAugmentor(Builder builder) {
this.output = builder.output;
Expand All @@ -57,6 +61,7 @@ public class QuarkusAugmentor {
this.finalResults = new HashSet<>(builder.finalResults);
this.buildChainCustomizers = new ArrayList<>(builder.buildChainCustomizers);
this.launchMode = builder.launchMode;
this.additionalApplicationArchives = new ArrayList<>(builder.additionalApplicationArchives);
}

public BuildResult run() throws Exception {
Expand All @@ -78,6 +83,7 @@ public BuildResult run() throws Exception {
.addInitial(ShutdownContextBuildItem.class)
.addInitial(ClassOutputBuildItem.class)
.addInitial(LaunchModeBuildItem.class)
.addInitial(AdditionalApplicationArchiveBuildItem.class)
.addInitial(ExtensionClassLoaderBuildItem.class);
for (Class<? extends BuildItem> i : finalResults) {
chainBuilder.addFinal(i);
Expand All @@ -91,15 +97,19 @@ public BuildResult run() throws Exception {

BuildChain chain = chainBuilder
.build();
BuildResult buildResult = chain.createExecutionBuilder("main")
BuildExecutionBuilder execBuilder = chain.createExecutionBuilder("main")
.produce(new SubstrateResourceBuildItem("META-INF/microprofile-config.properties"))
.produce(new SubstrateResourceBuildItem("application.properties"))
.produce(QuarkusConfig.INSTANCE)
.produce(new ArchiveRootBuildItem(root))
.produce(new ClassOutputBuildItem(output))
.produce(new ShutdownContextBuildItem())
.produce(new LaunchModeBuildItem(launchMode))
.produce(new ExtensionClassLoaderBuildItem(classLoader))
.produce(new ExtensionClassLoaderBuildItem(classLoader));
for (Path i : additionalApplicationArchives) {
execBuilder.produce(new AdditionalApplicationArchiveBuildItem(i));
}
BuildResult buildResult = execBuilder
.execute();

//TODO: this seems wrong
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright 2018 Red Hat, Inc.
*
* 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.quarkus.deployment.builditem;

import java.nio.file.Path;

import org.jboss.builder.item.MultiBuildItem;

/**
* An additional application archive
*/
public final class AdditionalApplicationArchiveBuildItem extends MultiBuildItem {

private final Path path;

public AdditionalApplicationArchiveBuildItem(Path path) {
this.path = path;
}

public Path getPath() {
return path;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
import io.quarkus.deployment.ApplicationArchive;
import io.quarkus.deployment.ApplicationArchiveImpl;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.AdditionalApplicationArchiveBuildItem;
import io.quarkus.deployment.builditem.AdditionalApplicationArchiveMarkerBuildItem;
import io.quarkus.deployment.builditem.ApplicationArchivesBuildItem;
import io.quarkus.deployment.builditem.ApplicationIndexBuildItem;
Expand Down Expand Up @@ -77,21 +78,22 @@ static final class IndexDependencyConfiguration {

@BuildStep
ApplicationArchivesBuildItem build(ArchiveRootBuildItem root, ApplicationIndexBuildItem appindex,
List<AdditionalApplicationArchiveMarkerBuildItem> appMarkers) throws IOException {
List<AdditionalApplicationArchiveMarkerBuildItem> appMarkers,
List<AdditionalApplicationArchiveBuildItem> additionalApplicationArchiveBuildItem) throws IOException {

Set<String> markerFiles = new HashSet<>();
for (AdditionalApplicationArchiveMarkerBuildItem i : appMarkers) {
markerFiles.add(i.getFile());
}

List<ApplicationArchive> applicationArchives = scanForOtherIndexes(Thread.currentThread().getContextClassLoader(),
markerFiles, root.getPath(), Collections.emptyList());
markerFiles, root.getPath(), additionalApplicationArchiveBuildItem);
return new ApplicationArchivesBuildItem(new ApplicationArchiveImpl(appindex.getIndex(), root.getPath(), null),
applicationArchives);
}

private List<ApplicationArchive> scanForOtherIndexes(ClassLoader classLoader, Set<String> applicationArchiveFiles,
Path appRoot, List<Path> additionalApplicationArchives) throws IOException {
Path appRoot, List<AdditionalApplicationArchiveBuildItem> additionalApplicationArchives) throws IOException {
Set<Path> dependenciesToIndex = new HashSet<>();
//get paths that are included via index-dependencies
dependenciesToIndex.addAll(getIndexDependencyPaths(classLoader));
Expand All @@ -103,7 +105,9 @@ private List<ApplicationArchive> scanForOtherIndexes(ClassLoader classLoader, Se
//we don't index the application root, this is handled elsewhere
dependenciesToIndex.remove(appRoot);

dependenciesToIndex.addAll(additionalApplicationArchives);
for (AdditionalApplicationArchiveBuildItem i : additionalApplicationArchives) {
dependenciesToIndex.add(i.getPath());
}

return indexPaths(dependenciesToIndex, classLoader);
}
Expand Down
40 changes: 40 additions & 0 deletions docs/src/main/asciidoc/getting-started-testing.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,46 @@ public class GreetingServiceTest {
----
<1> The `GreetingService` bean will be injected into the test

== Mock Support

Quarkus supports the use of mock objects using the CDI `@Alternative` mechanism. To use this simply override the bean
you wish to mock with a class in the `src/test/java` directory, and put the `@Alternative` and `@Priority(1)` annotations
on the bean. For example if I have the following service:

[source,java]
----
@ApplicationScoped
public class ExternalService {

public String service() {
return "external";
}

}
----

I could mock it with the following class in `src/test/java`:


[source,java]
----
@Alternative()
@Priority(1)
@ApplicationScoped
public class MockExternalService extends ExternalService {

@Override
public String service() {
return "mock";
}
}
----

It is important that the alternative be present in the `src/test/java` directory rather than `src/main/java`, as otherwise
it will take effect all the time, not just when testing.

Note that at present this approach does not work with native image testing, as this would required the test alternatives
to be baked into the native image.

== Native Executable Testing

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,27 @@ public void inject(Object test) {
while (c != Object.class) {
for (Field f : c.getDeclaredFields()) {
if (f.isAnnotationPresent(Inject.class)) {
BeanManager beanManager = Arc.container().beanManager();
List<Annotation> qualifiers = new ArrayList<>();
for (Annotation a : f.getAnnotations()) {
if (a.annotationType().isAnnotationPresent(Qualifier.class)) {
qualifiers.add(a);
}
}
Set<Bean<?>> beans = beanManager.getBeans(f.getType(),
qualifiers.toArray(new Annotation[qualifiers.size()]));
Bean<?> bean = beanManager.resolve(beans);
CreationalContext<?> ctx = beanManager.createCreationalContext(bean);
Object instance = beanManager.getReference(bean, f.getType(), ctx);
f.setAccessible(true);
try {
f.set(test, instance);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
BeanManager beanManager = Arc.container().beanManager();
List<Annotation> qualifiers = new ArrayList<>();
for (Annotation a : f.getAnnotations()) {
if (a.annotationType().isAnnotationPresent(Qualifier.class)) {
qualifiers.add(a);
}
}
Set<Bean<?>> beans = beanManager.getBeans(f.getType(),
qualifiers.toArray(new Annotation[qualifiers.size()]));
Bean<?> bean = beanManager.resolve(beans);
CreationalContext<?> ctx = beanManager.createCreationalContext(bean);
Object instance = beanManager.getReference(bean, f.getType(), ctx);
f.setAccessible(true);
try {
f.set(test, instance);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} catch (Throwable t) {
throw new RuntimeException("Failed to inject field " + f, t);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package io.quarkus.example.rest;

import javax.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class ExternalService {

public String service() {
return "external";
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicInteger;

import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObject;
import javax.servlet.http.HttpServletRequest;
Expand All @@ -47,13 +48,22 @@ public class TestResource {
@Context
HttpServletRequest request;

@Inject
ExternalService service;

private final AtomicInteger count = new AtomicInteger(0);

@GET
public String getTest() {
return "TEST";
}

@GET
@Path("/service")
public String service() {
return service.service();
}

@GET
@Path("/count")
public int count() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package io.quarkus.example.test;

import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Alternative;
import javax.interceptor.Interceptor;

import io.quarkus.example.rest.ExternalService;

@Alternative()
@Priority(1)
@ApplicationScoped
public class MockExternalService extends ExternalService {

@Override
public String service() {
return "mock";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Copyright 2018 Red Hat, Inc.
*
* 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.quarkus.example.test;

import static org.hamcrest.Matchers.is;

import org.junit.jupiter.api.Test;

import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;

@QuarkusTest
class TestMockTestCase {

@Test
public void testMockService() {
RestAssured.when().get("/test/service").then().body(is("mock"));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
Expand Down Expand Up @@ -94,6 +96,7 @@ private ExtensionState doJavaStart(ExtensionContext context, TestResourceManager
.setLaunchMode(LaunchMode.TEST)
.setClassLoader(getClass().getClassLoader())
.setTarget(appClassLocation)
.addAdditionalArchive(testClassLocation)
.setClassOutput(new ClassOutput() {
@Override
public void writeClass(boolean applicationClass, String className, byte[] data) throws IOException {
Expand Down Expand Up @@ -226,11 +229,13 @@ public void beforeEach(ExtensionContext context) throws Exception {
public Object createTestInstance(TestInstanceFactoryContext factoryContext, ExtensionContext extensionContext)
throws TestInstantiationException {
try {
Object instance = factoryContext.getTestClass().newInstance();
Constructor<?> ctor = factoryContext.getTestClass().getDeclaredConstructor();
ctor.setAccessible(true);
Object instance = ctor.newInstance();
TestHTTPResourceManager.inject(instance);
TestInjectionManager.inject(instance);
return instance;
} catch (InstantiationException | IllegalAccessException e) {
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
throw new TestInstantiationException("Failed to create test instance", e);
}
}
Expand Down