Add unit tests for Vigenere cipher (#3666)

This commit is contained in:
Alexandre Velloso 2022-10-26 01:57:51 +01:00 committed by GitHub
parent fd3386a0db
commit 7ef75980d5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 13 deletions

View File

@ -8,10 +8,11 @@ package com.thealgorithms.ciphers;
*/
public class Vigenere {
public static String encrypt(final String message, final String key) {
public String encrypt(final String message, final String key) {
StringBuilder result = new StringBuilder();
for (int i = 0, j = 0; i < message.length(); i++) {
int j = 0;
for (int i = 0; i < message.length(); i++) {
char c = message.charAt(i);
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
@ -39,10 +40,11 @@ public class Vigenere {
return result.toString();
}
public static String decrypt(final String message, final String key) {
public String decrypt(final String message, final String key) {
StringBuilder result = new StringBuilder();
for (int i = 0, j = 0; i < message.length(); i++) {
int j = 0;
for (int i = 0; i < message.length(); i++) {
char c = message.charAt(i);
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
@ -66,13 +68,4 @@ public class Vigenere {
}
return result.toString();
}
public static void main(String[] args) {
String text = "Hello World!";
String key = "itsakey";
System.out.println(text);
String ciphertext = encrypt(text, key);
System.out.println(ciphertext);
System.out.println(decrypt(ciphertext, key));
}
}

View File

@ -0,0 +1,37 @@
package com.thealgorithms.ciphers;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class VigenereTest {
Vigenere vigenere = new Vigenere();
@Test
void vigenereEncryptTest() {
// given
String text = "Hello World!";
String key = "suchsecret";
// when
String cipherText = vigenere.encrypt(text, key);
// then
assertEquals("Zynsg Yfvev!", cipherText);
}
@Test
void vigenereDecryptTest() {
// given
String encryptedText = "Zynsg Yfvev!";
String key = "suchsecret";
// when
String decryptedText = vigenere.decrypt(encryptedText, key);
// then
assertEquals("Hello World!", decryptedText);
}
}