Maven Project – Phone Number Validations and Testing via JUnit
Any web/mobile/console application should be error-free and hence it has to undergo a lot of validations. In this article, let us see how to validate phone numbers with and without country codes and test the same via JUNIT to check whether the given testing phone numbers are correct or not. Via a maven project, let us do the same.
Maven project and hence dependencies are in
First, let us write the validations that are needed for phone number validation
Now let us proceed to go into writing JUNIT
Here we need to note that
Grouped checks can be done by using assertAll and if there is anyone assert is wrong, then the whole statement will be failed. Instead of writing multiple assers, grouping can be done in this way. Moreover, sometimes there is a link like, all the conditions need to be met for a given business use case. During those times, assertAll helps a lot. Here in our example, to demonstrate the workflow, we have taken 2 sets
// In a grouped assertion all assertions are executed, and any // failures will be reported together. assertAll("phoneNumberValidation", () -> assertTrue(phoneNumberService.checkValidPhoneWithoutCountryCode("1357924680")), () -> assertTrue(phoneNumberService.checkValidPhoneWithoutCountryCode("1234567890")));
Actually below set of code got commented out. Hence we are getting all test cases passed
This is also a good facility to group items together and check. For example, to check all the person’s mobile number values with the expected values, this can be used, instead of one by one. On running the above code, we can see the below output.
// Let us uncomment now for the second time, as blocked portion is wrong. i.e. the first assertTrue. It is not a valid phone number // Though second assertFalse provides the correct result, as they are grouped with assertAll, we will get error only assertAll("phoneNumberValidationYieldingFalse", () -> assertTrue(phoneNumberService.checkValidPhoneWithoutCountryCode("firstname.lastname@example.org")), () -> assertFalse(phoneNumberService.checkValidPhoneWithoutCountryCode("12345Abc@d")));
Hence our output would be
Thus JUnit helps us to improve the quality of software. We need to use multiple asserts and also lot of test cases need to be tried out so that the software quality can be improved.
Please Login to comment...