Paul Buciuman
Paul Buciuman

Reputation: 335

Integration testing issue on inserting in data base

I am very new to testing and I'm playing right now with integration testing.

I'm writing this piece of code to insert a new entry in the database and test the before and after arrays. But for some reason, it seems to return false and I'm not sure if I'm doing everything right:

Here is the JUnit Class:

public class TestJunit {

private Question question;
private QuestionDAO questionDaoMock;

protected void setUp(){
    question = new Question();
    questionDaoMock = mock(QuestionDAO.class);  
    question.setQuestiondao(questionDaoMock);
}

@Test
public void testAdd() {
    questionDaoMock.openCurrentSessionwithTransaction();
    List<Question> currentQuestions = new ArrayList<Question>();
    currentQuestions = questionDaoMock.findAll();

    question.setChapterId(64);
    question.setText("Rezultatul calculului 54*2-76:2 este...");

    questionDaoMock.persist(question);
    currentQuestions.add(question);

    List<Question> newQuestions = new ArrayList<Question>();
    newQuestions = questionDaoMock.findAll();

    questionDaoMock.closeCurrentSessionwithTransaction();

    assertEquals(currentQuestions.size(), newQuestions.size());
}
}

This is my TestRunner:

public class TestRunner {
   public static void main(String[] args) {
  Result result = JUnitCore.runClasses(TestJunit.class);

  for (Failure failure : result.getFailures()) {
     System.out.println(failure.toString());
  }

  System.out.println(result.wasSuccessful());
   }
}   

I tried already the code in the testAdd() function separately in the main function just to check if insertion works and it does. I compared the arrays size and it works as well when I'm running from main method. What am I doing wrong?

Upvotes: 0

Views: 558

Answers (3)

Anton Petrov
Anton Petrov

Reputation: 326

Mock should not provide behaviour for you. You are need to do it yourself. For example:

questionDaoMock = Mockito.mock(QuestionDAO.class); 
Mockito.when(questionDaoMock.findAll()).thenReturn(Collections.emptyList());

Now when your code call method questionDaoMock.findAll()- Mockito return empty list for you.

I think You need to use real instance of QuestionDAO for this test.

Upvotes: 1

Paul Buciuman
Paul Buciuman

Reputation: 335

The problem seems to be with mocking the dao class. Am I doing that right? It actually returns a null array after the findAll() method (which Im sure it works)

Upvotes: 0

Himanshu Sarmah
Himanshu Sarmah

Reputation: 356

There should be a @Before annotation in the set up method, else Junit wont run the setUp() method before executing your testAdd() method.

Upvotes: 1

Related Questions