...
- "@Test" annotation has optional parameter "expected" that takes as values subclasses of Throwable
- It's used to verify if class throws the correct exception and annotation above test method looks like that: "@Test(expected=ExceptionName.class)"
Running tests
- To run a test just click on the test java file with right mouse button and choose "Run As -> 1 JUnit Test" or click with left mouse button on this file and use "Shift + Alt + X, T" shortcut.
- If you have eCoberture installed in your Eclipse IDE (see "Useful links" section at the end of this article) you can also click on the java file you want to test with right mouse button and choose "Cover As -> Coverage Configurations..." to see the code coverage of your test.
Example
This simple example show how to test single method in the InventoryService class.
InventoryService
...
.java fragment
This Tested method clear clears Entity fields after copyform copies it.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
@Service public class InventoryService { @Service public class InventoryService { // ... public boolean clearGeneratedOnCopy(final DataDefinition dataDefinition, final Entity entity) { entity.setField("fileName", null); entity.setField("generated", "0"); entity.setField("date", null); return true; } // ... } |
InventoryServiceTest
...
.java
In the test we want to check tested method return value and how many times we call "setField() " method was called. We mock only Entity beacase we only use it in methodit's the only variable used by the tested method.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
public class InventoryServiceTest { private InventoryService inventoryService; private Entity entity; @Autowired private DataDefinition dataDefinition; @Before public void init() { inventoryService = new InventoryService(); entity = mock(Entity.class); } @Test public void shouldClearGeneratedOnCopy() throws Exception { // given // when boolean bool = inventoryService.clearGeneratedOnCopy(dataDefinition, entity); // then assertTrue(bool); verify(entity, Mockito.times(3)).setField(Mockito.anyString(), Mockito.any()); } } |
Usefull links
- eCobertura - Tool to show how many code is covered by testsEclipse plugin for measuring and visualizing Java code coverage
- Mockito Documentation