Spring Boot REST API Unit Testing With JUnit. Unit Testing APIs is an important part of API testing because Unit Testing ensures that API components will function properly. In this article, we will learn how to cover Spring Boot REST APIs with JUnit. Spring Boot is an open- source framework for application creation, and where we create our APIs. There are many different variations and techniques to Unit Test APIs. ![]() I prefer the following combination: Spring Boot, JUnit, Mock. Mvc, and Mockito, because they are all open- source and support Java, which is my preferred language. To start, we have to have Intelli. J IDEA, as an IDE for development, and JDK8, for using Java for development. These are my personal preferences but Eclipse, Net. Used Tools For Completing Tutorial. For getting started discovering this tutorial, you have to use the following development tools. Tomcat 7; Eclipse IDE. I have looked all over for an answer to this question, but was not able to find one. I want to build a spring boot project with the maven command "mvn install", the. Beans, or even a simple text editor could also be used. Now, let’s setup a project. You can also participate - the source code is located here. We will be testing controllers and repository classes. In short, we have 4 controllers (Arrival. Controller, Departure. Controller, Users. Controller, Flights. Controller) and 4 repositories (Arrival. Repository, Departure. Repository, Users. Repository, Flights. Repository). We will write tests per controller (testing the size of the JSON Object, the status of the call to the endpoint and an assertion on one item from the JSON object) and tests per repository (inserting two new items in a table and making sure the return object is equal). Step 1 - Create an API Testing Project. Install Intelli. J IDEA. Make sure you have JDK installed (at least version 1. XXX). Now we will create a new project. Open Intelli. J and click “Create New Project.”4. Select Gradle, Java, and the JDK version. Name your project. Choose the project destination. If you did everything correctly, you should now see this window with an empty Java project: Step 2 - Add Dependencies. Now that we have a project, we need to setup the dependencies. You can use these dependencies since they are public. To do that, double click on your build. SNAPSHOT'. repositories {. Central(). maven { url "http: //repo. RELEASE"). apply plugin: 'java'. Dir "src/main/java". Dir "src/main/resources". Dir "src/test/java". Dir "src/test/resources". Name = 'blaze- demo- api'. Repackage {. main. Class = 'com. demo. Blaze. Meter. Api'. Management {. maven. Bom 'io. spring. platform: platform- bom: Brussels- SR2'. Central(). maven { url "http: //repo. Compatibility = 1. Compatibility = 1. Compile group: 'org. Compile group: 'org. Compile group: 'junit', name: 'junit'. Compile group: 'org. Step 3 - Write Your Unit Test via JUnit. In Intelli. J IDEA, go to the class that you want to test. Hit Cmd + Shift + T and a popup will appear. In the popup, select “Create New Test..”. Then, Intelli. J IDEA will create a file for writing the test in. The file will be created in the default place. In our case, if we are going to cover the class Arrival. Controller, it will create a test class with the path test/java/com/demo/controller. You can see this in the following screenshot: I personally prefer to group tests (as you can see in the same picture - there are 3 folders: bdd, rest, unit) according to the test types: REST, UNIT, BDD, etc. For that reason, I create the test classes by myself. For this example, Arrival. Controller. Test is located at the test/java/com/demo/unit/controller path. Here is the test class itself: package com. Arrival. Controller. Arrival. import org. Test. import org. Run. With. import org. Autowired. import org. Web. Mvc. Test. import org. Mock. Bean. import org. Spring. Runner. import org. Mock. Mvc. import java. List. import static com. Paths. ARRIVAL. import static com. Paths. VERSION. import static java. Collections. singleton. List. import static org. Is. Collection. With. Size. has. Size. import static org. Is. is. import static org. BDDMockito. given. Media. Type. APPLICATION_JSON. Security. Mock. Mvc. Request. Post. Processors. Mock. Mvc. Request. Builders. get. import static org. Mock. Mvc. Result. Matchers. json. Path. Mock. Mvc. Result. Matchers. status. Run. With(Spring. Runner. class). @Web. Mvc. Test(Arrival. Controller. class). Arrival. Controller. Test {. private Mock. Mvc mvc. private Arrival. Controller arrival. Controller. public void get. Arrivals() throws Exception {. Arrival arrival = new Arrival(). City("Yerevan"). List< Arrival> all. Arrivals = singleton. List(arrival). given(arrival. Controller. get. All. Arrivals()). will. Return(all. Arrivals). VERSION + ARRIVAL + "all"). Q1w. 2e. 3r. 4")). Type(APPLICATION_JSON)). Expect(status(). is. Ok()). . and. Expect(json. Path("$", has. Size(1))). Expect(json. Path("$[0]. City()))). public void get. Arrivals. By. Id() throws Exception {. Arrival arrival = new Arrival(). City("Yerevan"). given(arrival. Controller. get. Arrival. By. Id(arrival. get. Id())). will. Return(arrival). VERSION + ARRIVAL + arrival. Id()). . with(user("blaze"). Q1w. 2e. 3r. 4")). Type(APPLICATION_JSON)). Expect(status(). is. Ok()). . and. Expect(json. Path("city", is(arrival. City()))). }In this test class, we have two test methods, get. Arrivals() and get. Arrivals. By. Id(). The reason we have two is that we have two methods in the controller itself, so we want to test them both. The get. Arrivals() method does the following (code snippet above): Creates an Arrival entity and sets the test value for the city. Creates a list of Arrivals (because we will have just one member, it can be a singelton. List). Using given from mockito, makes sure the mocked Arrival. Controller will return a list of Arrivals. Performs a GET request to the mocked controller with the credentials and performs simple assertions. Status - 2. 00 (which is. Ok). The JSON object has one member. The JSON body has a city key with the value we set. The second test method does the same for the get. Arrivals. By. Id(). The difference is that it assumes one JSON object result instead of a list of Arrivals of JSON objects. That’s all. Now we can execute this single test by clicking the play button at the beginning of the line of the method name (see the following picture). The purpose of this execution is to make sure the test is working properly: After execution, you will see the results of test execution, including the status, count, and stacktrace. We can see that our test passed (on the left side), the number of tests (the progress bar is in the middle up top) and the stacktrace for execution. That’s it for that one controller. The next step will be to add tests for all controllers. Step 4 - Setting Up the Unit Tests for the APIs. Now, let’s test one API repository class with this unit test. This is a unit test that is covering the database testing part. For example, writing test data to the DB and afterward verifying it is properly stored. Like in the previous part, go to the Arrival. Repository class, hit Cmd + Shift + T and create a new test class via Intelli. J IDEA or by yourself. This is the code for that test class: package com. Arrival. import com. Arrival. Repository. Test. import org. Run. With. import org. Autowired. import org. Auto. Configure. Test. Database. import org. Data. Jpa. Test. import org. Test. Entity. Manager. Active. Profiles. Spring. Runner. import java. List. import static org. Assertions. assert. That. import static org. Auto. Configure. Test. Database. Replace. NONE. @Active. Profiles("test"). Run. With(Spring. Runner. class). @Auto. Configure. Test. Database(replace = NONE). Arrival. Repository. Test {. private Test. Entity. Manager entity. Manager. private Arrival. Repository arrival. Repository. public void when. Find. All() {. Arrival first. Arrival = new Arrival(). Arrival. set. City("Yerevan"). Manager. persist(first. Arrival). entity. Manager. flush(). Arrival second. Arrival = new Arrival(). Arrival. set. City("Israel"). Manager. persist(second. Arrival). entity. Manager. flush(). List< Arrival> arrivals = arrival. Repository. find. All(). assert. That(arrivals. Equal. To(9). assert. That(arrivals. get(7)). Equal. To(first. Arrival). That(arrivals. get(8)). Equal. To(second. Arrival). public void when. Find. All. By. Id() {. Arrival arrival = new Arrival(). City("Yerevan"). entity. Manager. persist(arrival). Manager. flush(). Arrival test. Arrival = arrival. Repository. find. All. By. Id(arrival. Id()). assert. That(test. Arrival. get. City()). Equal. To(arrival. City()). }In this test, we are using the H2 database for testing. This is common practice. Otherwise, you need to have the same type of database set up in all test/dev environments, maintain them and make sure you clean them up after test execution. Mojo – Plugins. Depending on their maturity, the available plugins are organized into groups as shown below. While using a pre- release or sandbox plugin might seem risky, it is your chance to provide feedback to the community such that the plugin can eventually reach production state. In order to guard against corrupted downloads/installations, it is highly recommended to verify the signature of the release bundles against the public KEYS used by the Codehaus Mojo developers. The following plugins have been released and are generally available for production use. However after the move from Codehaus to Mojo. Haus a lot of plugins have not been migrated (yet), so when the issue tracking is missing, the plugin has not been migrated. Plugin. Version. Description. Issue tracking. Application Server. Plugins that support integration with application servers. Packages various JBoss deployable archive files including AOP, ESB, HAR, SAR, and Spring. Git. Hubwas. 6central. IBM Web. Sphere Application Server 6. Supports various tasks within the Weblogic 8. Generators / Compilers / Translators. Plugins providing support for code generation, compilation and translation. Process ANTLRv. 2 grammars.- aspectjcentral. Weaves aspects with Aspect. J. Git. Hubaxistoolscentral. Axis wsdl. 2java and java. Git. Hubcastorcentral. . Source generation with Castor XML. Git. Hubcommons- attributescentral. Source generation for Commons Attributes.- GWTcentral. GWT. Git. Hubhibernate. Integration with Hibernate 3. Process IDL files into Java sources.- javacccentral. Process Java. CC grammars. Git. Hubjaxb. 2central. Generates Java classes from XML Schemas (and binding files) and creates XML Schemas from annotated Java classes, using JAXB2. Git. Hubjaxwscentral. JAX- WS wsgen/wsimport tooling support. Git. Hubjpoxcentral. Support for JPOX JDO.- jslintcentral. Provides fast and efficient JSLint code validation when developing Java. Script applications.- js importcentral. Provides Maven dependency management for Java. Script applications.- jspccentral. Provides support for JSP compilation.- rmiccentral. Generates rmi (Remote Method Invocation) stub and skeleton classes.- sablecccentral. Process Sable. CC grammars.- sqljcentral. Translates SQLJ source code to Java source code. Git. Hubxdocletcentral. Provides XDoclet functionality to Maven.- xmlbeanscentral. XML to Java binding via XMLBeans.- IDEs. Plugins that support integration with integrated developer environments. Creates Net. Beans Platform modules and applications. Git. Hub. Reporting. Plugins which generate reports. Checks Java libraries for binary and source compatibility with older releases. Git. Hubcoberturacentral. Code coverage via Cobertura. Git. Hubscmchangelogcentral. Simple Reporter that creates a changelog report using comments and tags from Subversion.- taglistcentral. Generates a report on various tags found in the code. Git. Hubjavancsscentral. Source measurement suite for Java. Git. Hubjdependcentral. Generates JDepend reports. Git. Hub. Testing. Plugins which support testing. Generate Code. Narc report against Groovy source code.- findbugscentral. Generates a Find. Bugs report. Git. Hubfitnessecentral. Fully integrated standalone wiki, and acceptance testing framework.- seleniumcentral. Supports automated web- application testing.- webtestcentral. Supports automated web- application testing using Canoo Web. Test- chronos- jmetercentral. Execute performancetests with jmeter and analyze the results.- chronos- surefirecentral. Analyze time spent in unittests used to measure performance- chronos- reportcentral. Create reports of performance testresults.- Tools. Miscellaneous tools available through Maven. Verifies classes against API signatures. Git. Hubappassemblercentral. Generates bin and Java Service Wrapper scripts for Java applications. Git. Hubbuild- helpercentral. Miscellaneous goals to support build process. Git. Hubbuildnumbercentral. Creates unique build number for each build. Git. Hubcassandracentral. Mojo's plugin for Apache Maven to allow controlling Apache Cassandra. Git. Hubditaotcentral. Support for DITA transformations using DITA Open Toolkit. Git. Hubexeccentral. Execution of system and Java programs. Git. Hubflattencentral. Flattens your pom. Git. Hubkeytoolcentral. Manipulates keys and keystores. Git. Hublatexcentral. Builds PDF documents from La. Te. X, Bib. Te. X and such. Git. Hublicensecentral. Tools to deal with licenses and thirdparties of a maven project. Git. Hubmrmcentral. Hosts a mock Maven Repository Manager for use when integration testing Maven plugins. Git. Hubouncecentral. Perform Ouncelabs Ounce code security scans.- rpmcentral. Assembles files into an RPM package. Git. Hubsiteskinnercentral. Apply a new skin on a published site generated by Maven- sqlcentral. Execution of SQL statements. Git. Hubtemplatingcentral. Filters sources the Maven Right Way. Git. Hubtidycentral. Sorts the sections of a pom. Git. Hubtruezipcentral. Manipulates archive files. Git. Hubversionscentral. Supports various tasks for updating the versions of components in the POM. Git. Hubvfscentral. Maven plugin for Apache Commons Virtual File System (VFS). Git. Hubwagoncentral. Transfer files between URLs. Git. Hubxmlcentral. XML transformation and validation. Git. Hub. The following are pre- releases of plugins. They have had releases, but are not deemed ready for production use yet. These are plugins which have been contributed but have not gained the attention of users or a committer interested in seeing it released. If you are looking for a plugin but do not see it in this list or the lists above, you should also check the Mojo. Haus team page in case the plugin hasn't been added to the list below yet. Plugin. Descriptionapidocs(no site)argouml. Generates images from Argo. UML diagrams. axis- archetype. This archetype is an example of using the Axistools and Cargo Maven Plugins. Executes the Ckjm bytecode analysis utility against a project. Debian Packaging tasks. Amazon Elastic Compute Cloud EC2 tasks. Uses Jax. Me 2 to generate JAXB source files from an XML schema. Execute expect like scripts over telnet/ssh sessions. Project graphing. Hibernate Doclet Plugin. Enable Maven users to develop applications for the Java Platform, Micro Edition. Generate an API difference report between two or more versions of code. Enhance files using Solarmetric's Kodo- JDO. Executes the Macker architectural rule checking utility against a project. Provides Natural. Docs capability to Maven. Provides console based editing of the project's pom. Retroweaver Maven Plugin. Provides a declarative mechanism for describing the runtime enviroment of Java applications. Helps configure Maven- related configuration files, such as settings. Similarity analysis reports. Generates String Bean. Doc reports from Spring configs. Spring Doclet Maven Plugin. Provides goals to send and receive syslog. Maven adapter of Visi. Broker command line tools. Uses Jax. Me 2 to generate JAXB source files from an XML schema. Generates Java classes from a given XML schema document using the Sun xjc task. Uses XSLTC to compile an XSL stylesheet into a translet (a set of Java classes). These are plugins which been deprecated or are no longer being maintained.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
November 2017
Categories |