JUnit is a framework for writing and running Unit tests
Mockito allows to create mocks (test doubles) which can
replace real collaborators of a class, thus making it possible to implement
some test cases.
JUnit and Mockito are often used together. JUnit is used to create the structure of test, while Mockito allow to specify some details of tests within the framework imposed by JUnit.
JUnit and Mockito are often used together. JUnit is used to create the structure of test, while Mockito allow to specify some details of tests within the framework imposed by JUnit.
I’d be covering an example of Mockito with Junit, (pre-requisite—Junit
basics)
Junit Theory:
@Test – Designate a test
@Before/@After – blocks execute before/After
@setup—setup methods executes before a test methods
@tear – executes after test methods
Mockito Theory:
@Mock / mock() – This creates a dummy object , in short mock
up an object if you don’t want to fetch any potential value out of it or methods
returning null or zero on each call
Ex- Below class will always be mocked
@Repository
public class OrderDao {
public Order getOrder(int irderId){
throw new
UnsupportedOperationException("Fail is not mocked!");
}
}
@InjectMocks – Creates an instance
@Spy/ spy() – Used to mock object which fetch some real
value
Ex—
@Service
public class PriceService {
public int getActualPrice(Item
item){
throw new UnsupportedOperationException("Fail
is not mocked!");
}
public int calculatePriceForOrder(Order
order){
int orderPrice = 0;
for (Item item :
order.getItems()){
orderPrice
+= getActualPrice(item);
}
return orderPrice;
}
}
MockitoAnnotations.initMocks(this)
) --to
initialize annotated fields. Without this call, these objects would be null
. Common mistake
with this approach is to forget this invocation.
If you have Any Annotated class – like Autowired
, above method has to be called otherwise these objects would be
null
I'd be covering example in my next blog
for any queries , please contact - jsapan4@gmail.com
Good article
ReplyDeleteThnx..
DeleteThnx..
Delete