Today is Friday, 23rd June 2017

Archive for the ‘JUnit’ Category


Java Eclipse Tutorial – Part 9: Running JUnit Tests

In this video tutorial, I will show you how to run JUnit tests Eclipse.

I will discuss the following topics:
• Create a Unit Test
• Running the Test

Please subscribe to this channel 🙂

Download Source Code

 

# Video Length
1 Installing the Eclipse IDE 03:18
2 Create a Java Application with Eclipse 03:44
3 Exploring the Eclipse User Interface 04:50
4.1 Searching and Navigating Source Code (part 1) 04:18
4.2 Searching and Navigating Source Code (part 2) 06:06
5 Generating Java Source Code 05:12
6.1 Refactoring Code - Extract Constants and Variables 04:13
6.2 Refactoring Code - Extract Methods, Rename Methods and Variables 04:19
7 Debugging Java Source Code 04:34
8 Adding JAR Files 05:17
9 Running JUnit Tests 05:08
10 Importing Projects 01:45
11 Exporting Projects 01:34
12 Setting Eclipse Preferences 04:09
Total 58:27

 

Video Transcript

Time – 00:00
Hi, this is Chad (shod) with luv2code.com. Welcome back to another tutorial on Eclipse. In this video, you’ll learn how to use JUnit in Eclipse.

Time – 00:12
I’ll cover the following topics: I’ll show you how to create a unit test and also how to run a unit test. Okay. Let’s get started.

Time – 00:23
We need to create a method to mask a credit card number. The credit card number is a 16-digit number. We only want to show the last 4 digits, and we’ll replace the other digits with an X. See the input number and the output number.

Time – 00:35
To test the code, we’ll make use of a testing framework called JUnit. This is available at junit.org. Eclipse has built-in support for JUnit, so there is nothing additional we have to download. In order to use JUnit, we have to create a test case. Inside of the test case, we’ll setup the input, we’ll execute the method, and then compare the result against the expected output. When you run the test, it will give you a pass-fail indicator. If you pass, you’ll see the green bar. If you fail, you’ll see the red bar. Of course, our goal is to see the green bar.

Time – 01:09
For this tutorial, I have an empty project. What I’ll do first is create a simple step for the method. The method will be called Mask and it will take a string for the credit card number. When doing unit testing, you’ll provide just a simple implementation of the method. Then, you’ll come back and you’ll add the real functionality to the method later.

Time – 01:31
Now, let’s add a new unit test for this. First, we’ll add a new source folder and call it test. Then, we’ll also add a new package using the same package name as our class. Then, we’ll go through and add an actual JUnit test called CreditCardUtilsTest. We’ll select the actual class that we’re going to test against CreditCardUtils, and we’ll keep all of the other defaults and then we’ll simply hit Finish.

Time – 02:16
Now, let’s add some code for this actual test. The first thing we’ll do is we’ll setup with the actual credit card number that we’re going to use for testing. Stub out some coding for executing assert. Here, I’ll go through and I’ll execute using this credit CreditCardUtils.mask method.

Time – 02:38
I’ll pass in the credit card number. Then, I’ll come over here and I’ll setup the expected value that should be returned, and then I’ll check to see if those two values are equal, so I’ll do assertEquals and give the expected value, the actual result.

Time – 02:59
Now, let’s go ahead and run the test. We’ll just do a right click. We’ll select Run As and JUnit test. In the top left corner, you’ll see the results. No, we have the red bar meaning that we failed, and we expect that because we didn’t put any real implementation code in our CreditCardUtils class.

Time – 03:18
All right, so let’s go ahead and add some real code. I’ll move into this method. I’ll remove that old piece of code and now I’ll say return. I’ll give the mask of the first 12 x’s and then I’ll do a substring, and I’ll get the last 4 characters of this number.

Time – 03:43
Now, what I like to do is go ahead and run the unit test. I’ll right click, say Run As, JUnit test, and then I’ll just check for the results in the top left corner, and wow we have a green bar. That’s great, so our unit test passed.

Time – 03:58
However, right now our unit test passed a very simple case. What happens if we give it bad data? Like we pass on the no value. What happens? I’m going to add another unit test here called test_nulls, and this will basically set the credit card number to null and it’ll call the method.

Time – 04:12
Now, this should give us an IllegalArgumentException. We have that setup as expected for this test, so let’ go ahead and save this and then we’ll run it and we’ll see what the results are. Run As, JUnit test, and now on the top left we have red, okay. One of the tests failed, so we passed in a null value and it didn’t like that no value. We need to fix this, so how can we do that?

Time – 04:38
In our code, we need to check the credit card number and see if it’s null. If it’s null, we’ll return a IllegalArgumentException and we’ll tell the user they must provide a credit card number. Let’s run our test one more time. Right click, say Run As, JUnit test, and then we’ll check the results in the top left, and good job. We have all green, so that means our unit test passed.

Time – 05:01
This wraps up our video on running JUnit testing Eclipse. Please subscribe to our channel to view more videos on Eclipse and Java. Click the thumbs up to like our video. Also, visit our website luv2code.com to download the Java source code used in this video.

Share


How to Generate a Random Password in Java

In this article, I’ll show you how to generate a random password in Java. This Java generator can be used by a website when a user forgets their password. The app will generate a new password and email it to the user. This article will simply focus on the code for generating the random password in Java. The password is randomly generated and follows these security rules:

  • at least 8 characters, max of 12
  • at least one uppercase
  • at least one lowercase
  • at least one number
  • at least one symbol @#$%=:?

Before we get into the coding of the Java implementation class, we will write a unit test. The unit test will verify that the generated password follows the security rules. In a previous post, I developed a regular expression to validate a given password. I will simply reuse that regular expression in our unit test.

@Test
public void generatePassword() {
// setup
String regex = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%=:\\?]).{8,12})";
// execute
String thePassword = PasswordUtils.generatePassword();
// assert
assertNotNull(thePassword);
assertTrue(thePassword.matches(regex));
}

This test sets up the regular expression for password validation. Then we execute the method PasswordUtils.generatePassword(). Once the password is generated, then we verify this is a valid password using the regular expression.

Now let’s move on to the implementation code. We can start with a very basic implementation, that will of course fail our test. This is what we’re starting out with.

public static String generatePassword() {
return null;
}

The test fails because we assert the password is not null. That is fine, since we’re following the TDD process of “write a failing test first”. Now, we need to provide the real implementation code. In the implementation, we need to follow the rules listed above. In brief, 8-12 characters, at least one upper, one lower, one digit and one symbol @#$%=:?. So in order to accomplish this, we’ll define the valid characters/digits for each rule.

Let’s walk thru the code to see how it works. The code starts with defining a constant for the maximum length of the password. We’ll also define a random generator that we use later.

public class PasswordUtils {
/**
* Minimum length for a decent password
*/
protected static final int MAX_LENGTH = 12;
/**
* The random number generator.
*/
private static java.util.Random r = new java.util.Random();

Now, we’ll define the range of valid characters, numbers and symbols that we’ll use in the password. This is accomplished with the code below:

/**
* I, L and O are good to leave out as are numeric zero and one.
*/
private static final String DIGITS = "23456789";
private static final String LOCASE_CHARACTERS = "abcdefghjkmnpqrstuvwxyz";
private static final String UPCASE_CHARACTERS = "ABCDEFGHJKMNPQRSTUVWXYZ";
private static final String SYMBOLS = "@#$%=:?";
private static final String ALL = DIGITS + LOCASE_CHARACTERS + UPCASE_CHARACTERS + SYMBOLS;
private static final char[] upcaseArray = UPCASE_CHARACTERS.toCharArray();
private static final char[] locaseArray = LOCASE_CHARACTERS.toCharArray();
private static final char[] digitsArray = DIGITS.toCharArray();
private static final char[] symbolsArray = SYMBOLS.toCharArray();
private static final char[] allArray = ALL.toCharArray();

If you have been in the IT industry for a while, you will know that certain characters do not make good password characters. Namely, the letters “I”, “L”, and “O”. They are easily confused with their number counterparts “1” and “0” so we’ll leave them out too.

Next we’ll cover the method implementation.

/**
* Generate a random password based on security rules
*
* - at least 8 characters, max of 12
* - at least one uppercase
* - at least one lowercase
* - at least one number
* - at least one symbol
*
* @return
*/
public static String generatePassword() {
StringBuilder sb = new StringBuilder();
// get at least one lowercase letter
sb.append(locaseArray[r.nextInt(locaseArray.length)]);
// get at least one uppercase letter
sb.append(upcaseArray[r.nextInt(upcaseArray.length)]);
// get at least one digit
sb.append(digitsArray[r.nextInt(digitsArray.length)]);
// get at least one symbol
sb.append(symbolsArray[r.nextInt(symbolsArray.length)]);
// fill in remaining with random letters
for (int i = 0; i < MAX_LENGTH - 4; i++) {
sb.append(allArray[r.nextInt(allArray.length)]);
}
return sb.toString();
}

In this method, we’re building the password string using concatenation. In this case, we have the option of using StringBuffer or StringBuilder. I chose StringBuilder since it is unsynchronized and results in faster code. Now, it is just a matter of choosing a random character from each of the arrays and append it to the string. After we have the first 4 characters/digits taken care of then we fill the remaining characters with random characters from the allArray. At the end of the method, we return a string version of the password.

Here is the complete code for the class.

package com.luv2code.password.util;
/**
*
* @author Chad Darby, darby@luv2code.com
*/
public class PasswordUtils {
/**
* Minimum length for a decent password
*/
protected static final int MAX_LENGTH = 12;
/**
* The random number generator.
*/
private static java.util.Random r = new java.util.Random();
/**
* I, L and O are good to leave out as are numeric zero and one.
*/
private static final String DIGITS = "23456789";
private static final String LOCASE_CHARACTERS = "abcdefghjkmnpqrstuvwxyz";
private static final String UPCASE_CHARACTERS = "ABCDEFGHJKMNPQRSTUVWXYZ";
private static final String SYMBOLS = "@#$%=:?";
private static final String ALL = DIGITS + LOCASE_CHARACTERS + UPCASE_CHARACTERS + SYMBOLS;
private static final char[] upcaseArray = UPCASE_CHARACTERS.toCharArray();
private static final char[] locaseArray = LOCASE_CHARACTERS.toCharArray();
private static final char[] digitsArray = DIGITS.toCharArray();
private static final char[] symbolsArray = SYMBOLS.toCharArray();
private static final char[] allArray = ALL.toCharArray();
/**
* Generate a random password based on security rules
*
* - at least 8 characters, max of 12
* - at least one uppercase
* - at least one lowercase
* - at least one number
* - at least one symbol
*
* @return
*/
public static String generatePassword() {
StringBuilder sb = new StringBuilder();
// get at least one lowercase letter
sb.append(locaseArray[r.nextInt(locaseArray.length)]);
// get at least one uppercase letter
sb.append(upcaseArray[r.nextInt(upcaseArray.length)]);
// get at least one digit
sb.append(digitsArray[r.nextInt(digitsArray.length)]);
// get at least one symbol
sb.append(symbolsArray[r.nextInt(symbolsArray.length)]);
// fill in remaining with random letters
for (int i = 0; i < MAX_LENGTH - 4; i++) {
sb.append(allArray[r.nextInt(allArray.length)]);
}
return sb.toString();
}
public static void main(String[] args) {
// generate the password
String thePassword = PasswordUtils.generatePassword();
// now print it out
System.out.println("Generated password is: " + thePassword);
}
}

Now that the code is complete, we can test it using our unit test. Based on the coding, the unit test passes with flying colors, green bar!

 

The source code is available here.

I hope that you have found this article useful. Enjoy!

Share


Unit Testing a Password Utility

In this post, we are going to develop a password utility. The utility has to support password validation.

Here are the password security rules for the application:

  • at least 8 characters, max of 12
  • at least one uppercase
  • at least one lowercase
  • at least one number
  • at least one symbol @#$%=:?

In regular TDD fashion, we’ll first set out to develop unit tests that will test the functionality of the application. Based on the security rules above, we will develop unit tests for the following conditions:

  • Test for null string
  • Test for empty string
  • Test for max of 12 characters
  • Test for at least one uppercase
  • Test for at least one lowercase
  • Test for at lest one number
  • Test for at least one symbol

There a number of ways to perform the validation on the password. However, the best solution for this is a regular expression. Agreed that it takes a bit of time to develop the regular expression, but the test cases will help drive us to the correct solution.

So let’s get started with the unit tests. Based on the information above, we have the following unit tests.

package com.luv2code.password.util;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Chad Darby, darby@luv2code.com
*/
public class PasswordUtilsTest {
@Test
public void validatePassword_Null() {
// setup
String password = null;
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_EmptyString() {
// setup
String password = "";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_Missing_OneNumber() {
// setup
String password = "Abcdefg#";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_Missing_OneUpperCaseLetter() {
// setup
String password = "abcdefg5#";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_Missing_OneLowerCaseLetter() {
// setup
String password = "ABCDEFG5#";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_Missing_OneSymbol() {
// setup
String password = "Abcdefg5";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_AllRulesMet() {
// setup
String password = "Abcdefg5#";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertTrue(actual);
}
@Test
public void validatePassword_LengthTooLong() {
// setup
String password = "Abcdefg5#abcdefgabcd";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
}

Now, we can move forward to the implementation. Essentially, we need to develop a method with the following signature:

/**
* Returns true if password matches the validation rules
*
* @param password
* @return
*/
public static boolean validatePassword(String password) {
return true;
}

Failing Tests

In true TDD fashion, this implementation will cause the majority of our tests to fail. It will fail for all invalid passwords. Our first run of the test cases will generate failures. Now, we can update the implementation to return the correct results. As I mentioned earlier, we’ll make use of a regular expression to validate the password.

package com.luv2code.password.util;
/**
*
* @author Chad Darby, darby@luv2code.com
*/
public class PasswordUtils {
private static final String VALID_PASSWORD_REGEX = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%=:\\?]).{8,12})";
/**
* Returns true if password matches the validation rules
*
* @param password
* @return
*/
public static boolean validatePassword(String password) {
return (password != null && password.matches(VALID_PASSWORD_REGEX));
}
}

Passing Tests

As you can see in the validatePassword method, the conditional checks to make sure the password is not null. This supports one of the first test cases. Now, to meet the validation rules, we make use of the regular expression:

((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%=:\\?]).{8,12})

Now, I know that looks like a really gnarly piece of gibberish, but let’s break it down one section at a time.

ExpressionDescription
(?=.*\\d)at least one digit
(?=.*[a-z])at least one lowercase
(?=.*[A-Z])at least one uppercase
(?=.*[@#$%=:\\?])at least one symbol @#$%=:?
{8,12}minimum of 8 characters, max of 12

That’s pretty much it. The regular expression is the bulk of development for this validation routine. It is nice that we were able to minimize the implementation to just a couple of lines of code. The unit tests provide coverage for the happy path, error conditions (null strings) and the edge cases.

The source code is available here.

Enjoy!

Share