Junit testing is an integral part of unit testing while developing any application. It makes sense at times to separate out testing of Business layer from DAO layer to avoid generation of test data everytime or may be DAO layer is being developed independently.
Frameworks like Mockito or Easymock comes handy when dealing with such situations where you only want to test one class or one method and mock any other dependencies by dummy objects.
Here is a simple example
@RunWith(MockitoJUnitRunner.class) public class UserManagerTest{ private static final String userName="kamal"; @InjectMocks private UserManager userManager=new UserManager(); @Mock private UserDAO userDAO; @Before public void initMocks() { MockitoAnnotations.initMocks(this); } //Remove the Ignore tag to execute the test case @Ignore @Test public void addUserTest() { try { Mockito.doNothing().when(userDAO).insertUser(userName); Mockito.when(userDAO.getUserDependencies(userId)).thenReturn(new UserDependencies("temp")); userManager.addUser(userName); } catch (Exception e) { fail("Test case failed"); // TODO Auto-generated catch block e.printStackTrace(); } } }
We are calling userManager.addUser(userName), but at the same time we are telling JUnit to do nothing (do not call the DAO layer), when you see this call to avoid data insertion. In addition there is another method which will check user dependencies (may be after adding user it check if there are some default depenedencies), where we tell Junit to instead of calling real DAO method and fecthing an objects, lets return a dummy object.