Getting started with Spring Boot Testing
When it comes to testing there are several different ways that you can write unit test to your application.Before doing any testing first we need to integrate testing framework, Spring boot provides spring-boot-starter-test to add dependency for testing framework.By adding this dependency in pom.xml it will cover most of the testing needed for an application.As spring-boot-starter-test covers wide range of unit test for test driven development framework.Spring-boot-starter-test come with below library-- Junit : This is used for all your unit testing
- Hamcrest : This is used for matching and assertions for unit test
- Mockito : This is a mocking framework to mock objects while writing unit test
- Spring Test : This is a testing tools for integration testing support
Add below dependency in pom.xml - As while creating maven project ,maven add junit library by default ,since spring-boot-starter-test already provides dependency for junit you can remove default junit dependency.In the above dependency scope is mentioned as test to signifies that the scope of this dependency is test. As maven generate default test class, we are going to utilize this and going to write basic test case.Open up AppTest class from the src/test/java folder.The AppTest class have many methods and constructor given delete them and construct a single test method. In the above codebase ,the test case has been written to test the testApp() method of PromoController class.The AssetEquals method is used to assert the value return from the method that we are testing.The simple way to create any test method is to annotate a method with @Test.Now run the test class by right click -> Run as-> Junit Test.After successful runs Junit tab would show green in color if test fails red color would show.There are multiple ways of running Jnuit, you can run Junit by right clicking on project folder run as maven test.One can also run Junit by command line if you have set up maven test command in command line ,simple mvn test command will work.
Unit Testing With Mockito
The previous test that we created was pretty simple.As application grows it is difficult to write unit test this way as in your application will have many dependency.Let's consider we are testing a class which has not been implemented yet and you have no idea of how this class has been implemented.In such case we make use of Mockito,as it provides functionality to mock object and it's behaviour.I am going to test the get method of PromoController.First add get method with Id in PromoController this method will return promotion for given Id. Create a class name PromoControllerTest as a test class to test above method. In the above class once you run as Junit test it will fail because while fetching value with Id 1 which is not available in DB when PromoController get method execute. To test this kind of scenario we have to mock this behavior.Add following code in the test class- Mockito is a popular mock framework which can be used in conjunction with JUnit. Mockito allows you to create and configure mock objects and it's behaviour.Mockito is a big topic in itself.I will explain basic of Mockito needed to mock an object. Given below some of basic annotations and methods used for mocking- 1. @Mock : To create a mock object we have to annotate by @Mock.By using @Mock at PromotionRepository it is going to mock the implementation this class. 2. @InjectMock : It will inject the mocks marked with @Mock to this instance when it is created. 3. MockitoAnnotations.initMocks(this) : When or where are these instances created? Well, it is done in this line, which resides in the setUp method 4. when() : This is used to output the behaviour of mock object.You call method inside and and thenReturn is used what are you expecting as a result. 5. verify() :It is used to verify the behaviour like how many times you are expecting this method to be called.Hamcrest Matcher
Though Junit provides feature for asserting and matching ,Hamcrest is a powerful framework used in conjunction with Junit. It provides declarative and readable approach for asserting and matching your test result. To make all matchers available in your file add an static import. This also makes it easier to find matchers through code completion. import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; Hamcrest provides many methods for matching test result ,I will explain the more basic and frequently used one-- allOf - matches if all matchers match
- anyOf - matches if any matchers match
- not - matches if the wrapped matcher doesn’t match and vice
- equalTo - test object equality using the equals method
- is - decorator for equalTo to improve readability
- hasToString - test Object.toString
- instanceOf, isCompatibleType - test type
- notNullValue, nullValue - test for null
- sameInstance - test object identity
- hasEntry, hasKey, hasValue - test a map contains an entry, key or value
- hasItem, hasItems - test a collection contains elements
- hasItemInArray - test an array contains an element
- closeTo - test floating point values are close to a given value
- greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo
- equalToIgnoringCase - test string equality ignoring case
- equalToIgnoringWhiteSpace - test string equality ignoring differences in runs of whitespace
- containsString, endsWith, startsWith - test string matching
Integration Testing Challenges
The last topic that I am going to cover in the continuation of spring boot is the challenges faced while integrating testing.Integration testing is all about testing all pieces of an application working together as they would in any live or production environment.Some major challenges found in traditional spring app-
1.Container are difficult to test
2.Spring context needs to be available
3.App/Test start up can be slow
4.Database state needs to be consistent
In compare to tradition spring apps the spring boot apps have below challenges discovered-
1.No container ,easier to start up
2.Spring context auto configuration
3.App/Test start up can be slow
4.Database state needs to be consistent
Comments
Post a Comment