Issue
i am just doing unit test for my class named Card
public class Card{
private KeyStore kestore;
private Cipher cipher;
public Card(){
}
public void generateRandom(){
keyStore = KeyStore.getInstance("AndroidKeyStore");
keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
keyStore.load(null);
keyGenerator.init(new
KeyGenParameterSpec.Builder(KEY_NAME,
KeyProperties.PURPOSE_ENCRYPT |
KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(
KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
keyGenerator.generateKey();
}
public void init(){
cipher = Cipher.getInstance(
KeyProperties.KEY_ALGORITHM_AES + "/"
+ KeyProperties.BLOCK_MODE_CBC + "/"
+ KeyProperties.ENCRYPTION_PADDING_PKCS7);
keyStore.load(null);
SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME,
null);
cipher.init(Cipher.ENCRYPT_MODE, key);
}
}
and the below is my unit testing coding.
public class cardTest extends AndroidTestCase{
Card card;
@Override
protected void setUp() throws Exception {
super.setUp();
card = new Card();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public class testgenerateRandom(){
card.generateRandom();
}
public class testinit(){
card.init();
}
}
so in the above unit test,
the testinit() will call the init of the Card class. there keystore becomes null. i already initialized the keystore in generateRandom() which is the first test case.
whenever the first test case (testgenerateRandom()) done, the card instance becomes null. so that keystore also becomes null
why is the card instance becomes null? can any help me in that?
Solution
Keep in mind that JUnit will create a new instance of your cardTest
class for each test method it runs, meaning testgenerateRandom()
won't be called before testinit()
as you probably expect, and both methods will use different instances of Card
. Make sure to configure the instance under test properly in setUp()
for each test method.
Answered By - Egor
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.