Gold Win
Gold Win

Reputation: 7

how to unit test block of code that has db call and subsequent line depending on the db call

How to write junit test for testing the block of function that has the db call and the subsequent lines based on the db call result? any samples or example is appreciated

My function to test:

public String functionality(String input)
{
      String readDBValue = db.giveMeValue();

      if (input.contains(readDBValue))
      {
         return input;
      }
      else 
      {
        return null;
      }
    }

My Junit4 test case:

public class JunitTest
{
    @Test
    public void  testFunctionality()
    {
        String inputTst = "new input";
        String expectTst = "new input";
        assertEquals(functionality(input), expectTst);
    }
}

How to test the line in functionality that returns some value from database from a dependent function?

Upvotes: 0

Views: 416

Answers (1)

Hamish Smith
Hamish Smith

Reputation: 8181

Can you mock the DB and inject the mock into whatever class you are testing?

Using a test double of some description for the database will speed up your tests and allow you to specify the behaviour of the database calls so you can test branches in your code.

Edited 2019-04-28 18:17:00+13:00: Adding a code sample to illustrate.

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

public class TestMyClass {

    @Test
    public void test1()  {
        // create mock
        MyDatabase mockDb = mock(MyDatabase.class);

        // set behaviour required in test
        when(mockDb.giveMeValue()).thenReturn("new input");

        // inject mock into object being tested
        MyClass objectUnderTest = new MyClass(mockDb);

        // use mock in test....
        assertEquals(objectUnderTest.functionality("input"), "new input");
   }
}

Upvotes: 1

Related Questions