我已经尝试为我的Android应用程序创建一些单元测试,它们正在使用来自数据库的数据,但是我遇到了一个问题,可以在运行测试后立即通过堆栈跟踪报告的简要描述:
java.lang.NullPointerException at com.projects.sanchellios.slovo.MockDatabaseConstructor.insertWordIntoDatabase(MockDatabaseConstructor.java:64)
......等等。
我的想法是创建一个数据库和databaseHelper实例的模拟,它使用实际的SQLiteDatabase类和我项目的SQLiteOpenHelper实例,这里是代码:
@RunWith(MockitoJUnitRunner.class)
public class MockDatabaseConstructor {
@Mock
private SQLiteDatabase database;
@Mock
private DatabaseHelper databaseHelper;
public static String LESS_THAN_15 = "LESS_THAN_15";
public static String MORE_THAN_15 = "MORE_THAN_15";
public MockDatabaseConstructor(Context context, String fillDbScenarioCommand){
databaseHelper = DatabaseHelper.getInstance(context);
database = databaseHelper.getWritableDb();
if(fillDbScenarioCommand.equals(LESS_THAN_15)){
createLessThan15WordsInDb();
}else if(fillDbScenarioCommand.equals(MORE_THAN_15)){
createMoreThan15WordsInDb();
}
}
private void createLessThan15WordsInDb(){
insertWordIntoDatabase("good", "добро, хорошо", 10, 1); //score=10
insertWordIntoDatabase("evil", "зло", 8, 2); //score=4
insertWordIntoDatabase("mock", "макет, ложный", 5, 5); //score=1
}
private void createMoreThan15WordsInDb(){
insertWordIntoDatabase("good", "добро, хорошо", 10, 1); //score=10
insertWordIntoDatabase("evil", "зло", 8, 2); //score=4
insertWordIntoDatabase("mock", "макет, ложный", 5, 5); //score=1
}
private void insertWordIntoDatabase(String wordValue,
String translations,
int correctAnswers,
int incorrectAnswers){
double score = getScore(correctAnswers, incorrectAnswers);
ContentValues translatedWordValues = new ContentValues();
translatedWordValues.put(WORD_COL, wordValue);
translatedWordValues.put(TRANSLATIONS_COL, translations);
translatedWordValues.put(CORRECT_COL, correctAnswers);
translatedWordValues.put(INCORRECT_COL, incorrectAnswers);
translatedWordValues.put(SCORE_COLUMN, score);
database.insert(TRANSLATED_WORDS_TABLE, null, translatedWordValues);
}
private double getScore(int correct, int incorrect){
return (double)correct/(double)incorrect;
}
public SQLiteDatabase getDatabase(){
return this.database;
}
}
这里是描述,unitTest如何使用该类:
@RunWith(MockitoJUnitRunner.class)
public class QuizTest {
private final int TEST_LIMIT = 15;
private MockDatabaseConstructor mockDatabase;
private SQLiteDatabase database;
private Quiz quiz;
@Mock
Context mockContext;
@Before
public void setUp() {
mockDatabase = new MockDatabaseConstructor(mockContext, MockDatabaseConstructor.LESS_THAN_15);
database = mockDatabase.getDatabase();
quiz = new Quiz(mockContext, TEST_LIMIT);
}
@Test
public void TestFirstWordPoll() {
Word word = quiz.pollNextWord();
assertEquals("Wrong word at the beginning of queue", "good", word.getWordValue());
}
}
也许,我对自己的表现完全错了,但我真的需要帮助。
那么,如何使用Mockito模拟数据库,以使其可用于任何单元测试?