I always try to stick to one assertion per test but sometimes I'm having troubles in doing so.
For example.
Say I've written a cryptographic class that encrypt and decrypts strings.
public class CryptoDummy
{
public string Decrypt(string value)
{
}
public string Encrypt(string value)
{
}
}
How would I create my unit test if the decryption is depended upon the output of the encryption ?
Most of my tests if not all up until now are composed of one method call per test and one assertion per test.
So to the point, is it fine to have multiple calls per test and assert the final results made by the method I called last ?
public class CryptoDummyTest
{
private static CryptoDummy _cryptoDummy;
// Use ClassInitialize to run code before running the first test in the class
[ClassInitialize]
public static void MyClassInitialize(TestContext testContext)
{
_cryptoDummy = new CryptoDummy();
}
[TestMethod]
public void Encrypt_should_return_ciphered_64string_when_passing_a_plaintext_value()
{
const string PLAINTEXT_VALUE = "[email protected]";
string cipheredString = _cryptoDummy.Encrypt(PLAINTEXT_VALUE);
Assert.IsTrue(cipheredString != PLAINTEXT_VALUE);
}
[TestMethod]
public void Decrypt_should_return_plaintext_when_passing_a_ciphered_value()
{
const string PLAINTEXT_VALUE = "[email protected]";
string cipheredString = _cryptoDummy.Encrypt(PLAINTEXT_VALUE);
string plaintextString = _cryptoDummy.Decrypt(cipheredString);
Assert.IsTrue(plaintextString == PLAINTEXT_VALUE);
}
}
Thank you in advance.
You shouldnt have one test depending upon another. The best way to do this would be to output the encrypted text somewhere and save it. Then on the decrypt text test you could start with an encrypted text and test you decrypt it correctly. If you use the same encryption key (which is fine for testing) the encrypted string will always be the same. So change your second unit test to something like this:
[TestMethod]
public void Decrypt_should_return_plaintext_when_passing_a_ciphered_value()
{
const string PLAINTEXT_VALUE = "[email protected]";
string cipheredString = "sjkalsdfjasdljs"; // ciphered value captured
string plaintextString = _cryptoDummy.Decrypt(cipheredString);
Assert.IsTrue(plaintextString == PLAINTEXT_VALUE);
}
This sounds strange to me. My opinion of unit testing is, that a unit test will test one special situation with a definite set of data provided. If one test depends on the result of another test, the result is not deterministic. The second thing is, that you can not be asured of the order the tests are executed!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With