Answer the question
In order to leave comments, you need to log in
How to create a mock database using Mockito?
Hello!
I decided to slowly cover my Android application with unit tests, it's time to go. But here I ran into a problem:
java.lang.NullPointerException
at com.projects.sanchellios.slovo.MockDatabaseConstructor.insertWordIntoDatabase(MockDatabaseConstructor.java:64)
@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;
}
}
@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());
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question