Java Reference
In-Depth Information
C
@RunWith(UnitilsJUnit4TestClassRunner. class )
public class UserFacadeImplUnitilsTest {
@TestedObject
private UserFacadeImpl facade;
D
@Mock
@InjectIntoByType
private UserDao dao;
@Test
public void testGetUserById() {
int id = 666;
User user = newUserWithTelephones();
expect(dao.getUserById(id)).andReturn(user);
replay();
UserDto dto = facade.getUserById(id);
assertUser(dto);
// verify();
}
E
}
In order to use Unitils, first the test class must either extend the superclass that pro-
vides support for the testing framework being used (like UnitilsJUnit4 ) or annotate
it with the proper JU nit runner; in this example, we opted for the latter C . The next
step is to declare fields representing the object being tested and the mocks; Unitils
provides annotations for both, as shown in D . Notice that the @Mock annotation will
create an EasyMock mock; although Unitils mock support is provided through mod-
ules, currently only EasyMock is available. Next comes the test method itself E , whose
content is pretty much the same as before; the only differences are that it uses Unitils'
replay() method instead of EasyMock's (that's why in B we statically imported any
methods explicitly, instead of using *) and it isn't necessary to call verify() (Unitils
will automatically do that after the test is run, although such behavior could also be
changed by modifying a property).
Compare this example with chapter 18's (shown in listing 18.5). Although the core
of the class (the test method itself) is the same, this new example requires much less
setup. It might not sound like a big difference in these two simple examples, but in a
real project, with dozens or even hundreds of such test cases, such small local
improvement results in a big gain in the global productivity.
Behind the scenes, Unitils uses two modules, inject and easymock . Because we
didn't configure anything, Unitils loaded all modules. The default value for the mod-
ules property is
unitils.modules=database,dbunit,hibernate,mock,easymock,inject,spring,jpa
If this property isn't overridden, Unitils will load all modules, which means more
implicit setup methods need to be called before and after each test. If you don't need
all modules, set this property with just the necessary ones. In our example, it would be
unitils.modules=easymock,inject
 
 
Search WWH ::




Custom Search