Programmatically add Maven repository to project in Java

In my tests I have a project created like this:

        Project project = ProjectBuilder.builder()
                                        .build();

How do I add a Maven repository to this project? The repository URL is known, let’s assume it’s “http://maven.example.com/repository/example”.

If I want to programmatically add a dependency, I can do it like this:

                                        project.getBuildscript()
                                               .getConfigurations()
                                               .getByName(classpath.value())
                                               .getDependencies()
                                               .add(someDependency);

But for the dependency to be resolved, it’s necessary to have the corresponding Maven repository available.

So how do I add a Maven repository to the project?

I know it’s possible to do something like this:

                                        project.getBuildscript()
                                               .getRepositories()
                                               .add(ArtifactRepository repository)

but how do I adequately initialize that ArtifactRepository in tests?

When you call project.getBuildscript().getRepositories(), the type returned is a RepositoryHandler. Don’t use the generic add() method with the ArtifactRepository interface, but instead use the maven() method, which takes a configuration Action with the appropriate MavenArtifactRepository implementation (Java 8+):

project.getBuildscript()
       .getRepositories()
       .maven(mavenRepository -> {
           mavenRepository.setUrl(url);
       });

Thanks a lot, that helped!