Return dynamic result from mock with Mockito

4 03 2009

Sometimes you need to stub a class only for a method and you may need to add some behavior to that stubbed mehod like get a value from a map and return it.
Instead of just returning an object for the stubbed method like:

when(mock.aMethod(anyString())).thenReturn("a static result");

you can return a dynamic result by using stubbing with callbacks feature of Mockito.

when(mock.aMethod(anyString())).thenAnswer(new Answer<MyObject>() {
     MyObject answer(InvocationOnMock invocation) {
         Object[] args = invocation.getArguments();         
         //you can do some stuff using args
         return ...;
     }
 });

In answer method you can access the mocked object itself :

Object mock = invocation.getMock();

By the way, this brings a bit complexity to your test. If you don’t really need it, do not use it. 
Don’t forget simplicity.





Unit Testing Repositories with DbUnit and Spring

28 05 2008
In this post, I will create a base class for repository tests. I used DBUnit to populate database configured in a testContext.xml. And I used Spring test annotations to wire test classes with dataSource and repositories.
Requirements
* Spring 2.5
* DbUnit 2.2.2
* Junit 4.4Here you are

import javax.sql.DataSource;

import org.dbunit.DataSourceDatabaseTester;
import org.dbunit.IDatabaseTester;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:*testContext.xml" })
@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class })

public abstract class AbstractRepositoryTest {

 private IDatabaseTester databaseTester;

 private DataSource dataSource;

 @Autowired
 public void setDataSource(DataSource dataSource) {
     this.dataSource = dataSource;
 }

 @Before
 public void setUpDatabase() throws Exception {
    try {
      databaseTester = new DataSourceDatabaseTester(dataSource);
      databaseTester.setTearDownOperation(DatabaseOperation.DELETE_ALL);
      IDataSet dataSet = getDataSet();
      databaseTester.setDataSet(dataSet);

      databaseTester.onSetup();
  } catch (Exception e) {
     e.printStackTrace();
     throw e;
  } } protected abstract IDataSet getDataSet() throws DataSetException ; @After public void tearDownDatabase() throws Exception { if (databaseTester != null) { databaseTester.onTearDown(); } } }

And here is a saimple example test for MyRepository.

import java.util.List;

import javax.sql.DataSource;

import org.dbunit.DataSourceDatabaseTester;
import org.dbunit.IDatabaseTester;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.csv.CsvURLDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.junit.After;import org.junit.Assert;
import org.junit.Before;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;

public class MyRepositoryTest extends AbstractRepositoryTest {

 private MyRepository myRepository;

 @Autowired
 public void setMyRepository(@Qualifier("myRepository") MyRepository myRepository) {
      this.myRepository = myRepository;
 }

 protected IDataSet getDataSet() throws DataSetException {
    // returns CVS files in the currenct directory
    return new CsvURLDataSet(getClass().getResource(""));
}

 @Test
 public void listMyXEntities() {
    List xList = myRepository.listXEntities();
    Assert.assertEquals(3, xList.size());
  }
}

I really like the simplicity that comes with annotations!

PS : In the AbstractRepositoryTest’s setUpDatabase() method, there is a try-catch. I added it because in  org.springframework.test.context.junit4.SpringMethodRoadie.java (v1.13), at line 335, there is a catch like :

catch (FailedBefore ex) {
}
So in case of any exception in set up, you loose it.




Database Unit Testing in .NET and Rollback

17 08 2006

In .Net, to rollback transactions after unit tests run, you can use Enterprise Services.

For more information, you can follow the link: http://weblogs.asp.net/rosherove/articles/dbunittesting.aspx





NUnit ve .config Dosyası

2 05 2006

Uygulamanız .config dosyası içeriyorsa ve NUnitle test yazmışsanız konfigürasyon işini testlerinize de bildirmelisiniz. Bunun için .config dosyasını test altına kopyalayın ve

  1. Eger myProject.Tests.dll gibi direk bir test “assembly” yüklüyorsanız, dosyanın adı myProject.Tests.dll.config yapın.
  2. Eger myProject.Tests.unit gibi direk bir NUnit projesi yüklüyorsanız, dosyanın adı myProject.Tests.config yapın.
  3. Eger myProject.Tests.csproj yada myProject.Tests.sln gibi NUnit’in Visual Studio desteğini kullanarak bir VS proje yada çözümü yüklüyosanız, dosyanın adı myProject.Tests.config yapın.

Ve bu işin çalışıp çalışmadığını da test etmek için test projesi .config dosyasına;

<add key=”testKey” value=”I am a test key”/>

ekleyin.

Ve test olarak şunu yazın:

[Test]

public void CheckConfigFile()
{
Assert.AreEqual( “I am a test key”, System.Configuration.ConfigurationSettings.AppSettings["testKey"] );

}

Başınız ağrısınız, testleriniz yeşil, kodunuz temiz olsun…

Kaynak : How NUnit Finds Config Files http://nunit.com/blogs/?p=9#respond








Follow

Get every new post delivered to your Inbox.