JUNIT & MOCKITO

 JUNIT & MOCKITO




Important Links:-

1) https://code.google.com/archive/p/mockito/downloads


Advantages of Unit Testing:-
------------------------------------

1) Assure Quality

2) Run Fast

3) Regression Suite


=> While Unit Testing we don't test the application end to end.

=> JUnit doesn't provide the Mocking API.


Testing Framework:-
-------------------------

A Testing Framework provides 3 important things:-

1) An easy API to write tests

2) A way to assert for the results

3) Run and report results


Writing Tests:-
------------------

JUnit3 -------------------> junit.framework.TestCase

JUnit4 -------------------> Annotations


Annotations:-

i) @Test:- used to mark each and every test methods

ii) @Before:- Any method that is marked with @Before annotation will be run before each test method that we write in a test class.

iii) @After:- Any method that is marked with @After annotation will be run after every test method.

iv) @BeforeClass:-  If we mark a method with this annotation then that method will run only once for the entire test class right at the beginning.

v) @Ignore:- If we mark our test with this annotation then those test will be ignored.


=> JUnit also provides easy to use static methods in the assert class.which we can use to assert the expected results vs actual results that thumb back from the methods.

import static org.junit.Assert.*;

     |              |                       |

     |              |                       |

     |              |                       |

    \/              \/                       \/

  assertNotNull         assertEquals       assertSame


1) assertNotNull:- It will take an object and if that object is null then assertion will fail and our test will also fail.

2) assertEquals:- It checks for value of two objects.

3) assertSame:-  It checks for the references of the two objects.


Running the Tests:
----------------------

1) BlockJunit4ClassRunner.class:-
   -------------------------------------

Junit provides a BlockJunit4ClassRunner.class.We run this from command line, pass this test classes as the command line arguments to this class and this class will scan through our test classes for the annotations

like the test annotation before the annotation, run all the setup and cleanup methods on all our test methods and it will report out the results of all the tests that we have passed or failed. This is the default Junit test runner.


2) @RunWith(SpringJUnit4ClassRunner.class):- 
    ------------------------------------------------------

  The above class exends this class and implements the JunitRunner framework for writing integration tests while working with spring-based application. This annotation can be used to configure Runner when we run our test.


Q1) Which annotation can be used to setup data for each test method?

Ans:- @Before


Q2) Which assertion can we use to compare and see if the expected and actual values are equal?

Ans:- assertEquals


Q3) Which of the following is the default JUnit test runner?

Ans:- BlockJunit4Runner.class


Q4) Which JUnit annotation should be used to mark each test method?

Ans:- @Test


JUNIT5:-
--------------

Migrating from JUnit 4 to 5:
---------------------------------

1) Modularized

2) JUnit Platform

3) JUnit Vintage

4) Java 8 Feature Support


Annotations:-
-------------------

1) BeforeEach

2) AfterEach


* The easiest way to work with JUnit 5 is to create a Maven Java project, add the JUnit 5 dependencies, write the supercool tests and execute them.


Maven:
---------

-> Build Tool

-> Project Management Tool


Build:-
----------

1) Compile

2) Run Tests

3) Package Jar Package War

4) Deploy to Server


-> Maven uses Convention over Configuration


myproject

     | mvn install

     |--src/main/java

     | compile

     |--src/main/resources

     | run

     |--src/test/java

     | package

     |--src/test/resources

     | deploy



Archetypes:-
---------------

-> standalone

-> webapp

-> ear


Maven clean - will clean everything inside the target directory of the project folder

Maven install - compile the source code, test the file and build our jar files under the target directory


JUnit 5 Dependencies:-
------------------------------

1) junit-jupiter-engine

2) junit-vintage-engine - for supporting earlier versions of JUnit

3) junit-platform-runner - has the support to run unit tests

4) junit-jupiter-api - provides the platform that we want to use in our test


In JUnit 5 include @RunWith(JUnitPlatform.class) before the test to run our class.



Mockito in Action:-
-----------------------

Mocking:-  Testing in Isolation

--------------

Mock means to mimic or to emit it. We use it for Unit Testing.


A -----------------------------> B

Mock


1) Each units are tested on its own.

2) Dependencies are tested.


ReservationController

|

|

|

|

|

\/

        ReservationBO

|

|

|

|

|

\/

        ReservationDAO------------------->DB



ReservationController

|

|

       Stubbing and | Verifying

Setting Expectations |

|

|

\/

         ReservationBO




@Mock

Stub and Setting Expectations ------------------------------>                when

thenReturn

thenThrow



Verification --------------------------> verify, matchers, etc



-> Mocking enables it or complements Unit Testing by allowing us to mock out all the dependent classes and the methods that are used.


Q1) What is the first step in mocking?

Ans:- Stubbing and setting expectations


Q2) Which annotation can be used to mock an object?

Ans:- @Mockito


Q3) Which method in the Mockito API should be called to initialize the mocks?

Ans:- initMocks


Q3) Which static method can be used to stub out the method calls on a mocked object?

Ans:- when


Q4) While using the when method to stub which method should be used return a value?

Ans:- thenReturn


Q5) Which methods in the JUnit API can be used to verify the results?

Ans:- assert methods


** In JUnit 5, Assertions methods are present in org.junit.jupiter.api.Assertions.* package. So we have to import import static org.junit.jupiter.api.Assertions.*;


Mockito JUnit 5 Dependencies:-
------------------------------------------

1) junit-jupiter

2) mockito-junit-jupiter


Annotations Used:-
-------------------------

1) @ExtendWith(MockitoExtension.class)

2) @Mock - used to mock the interface and service class

3) @InjectMocks - used to mock class into which the mock should be injected in the test class


Test Coverage:-
--------------------

Code Coverage:-
---------------------

-> Install EclEmma

-> Measure

-> Improve


1) Test Coverage or Code Coverage is the number of lines of codes that is tested when our unit tests are run against the source code.


2) This includes 

-> Conditional Statements

-> Loops

-> The no of parameters that we pass into a method

-> The type of parameters that we pass into a method

-> etc.


3) We measure Code Coverage using tools.These tools run our test against the source code and will give us the % of Code Coverage and will also show us which lines of codes are tested, which are not tested 

    and which need more testing.


e.g.- if(accountHasMoney) {

doTransfer();

        } else {

throwException();

           }


Open Source Tools:

--------------------------

Popular Ones:

1) EclEmma --> Jacoco Eclipse Plugin

2) Cobertura

3) JTest


       Maven

CI ----------------> Jenkins/

      \Ant



The FIRST Principle:
--------------------------

FAST, INDEPENDENT, REPEATABLE, SELF-VALIDATING, TIMELY


Test Doubles:-
--------------------

1) Gerard Meszaros - Common Patterns across unit testing frameworks


2) Test Doubles allow us to mock out the actual objects that act as a Stunt Doubles and they allow us to write great unit test.


The 5 Test Doubles patterns are:-

1) Dummy :- These are the objects that are passed as a parameter but are not really required for testing a scenario.

2) Stubs:- Thses provide fixed answers or return values and will do only what we asked them to do. We can create stubs using the when class and the thenReturn() method in Mockito.

3) Mocks:- Mocks are little more than Stubs. They can throw Exceptions as well as they allow us to verify if certain other methods were called when we are testing a method.

4) Fake:- These are the shortcuts like in-memory databases that are rarely used in Unit Testing.

5) Spies:- They are Stubs that can spy or record any side-effects when we are testing a particular method.


3) Test Doubles are design patterns that have to do Unit Testing Frameworks.

4) They derive their names from Stunt Doubles.

5) They act as if they are real objects but they only do what we ask them to do allowing us to write great Unit Tests.


Partial Mocking using Mockito Spy:
--------------------------------------------

1) If we want to do the partial mocking we can mark a class with @Spy annotation and real methods will be called by default and if we want to stub out we should use the doReturn() syntax.

2) Spy is going to use the real object.

3) All the real objects will be called by Mockito when we use the Spy whereas Mock is Mockito's own version of object and nothing happens unless we stub out the particular calls.

4) A better way of handling spies or doing partial mocking in Mockito is not to use Spy. We simply use the Mock and call thenCallRealMethod() method for partial Mocking.


Maven and JUnit Quickstart:
-----------------------------------

Plugin Based

compiler- compile

surefire- run test

etc


pom.xml

coordinates

plugins

dependencies



Parameterized JUnit:
--------------------------

1) It was introduced in JUnit 4.

2) It allows us to pass different types of data sets and assert for different results within one single test method.

e.g.- int result = add(int num1, num2)

3) We can execute one single test multiple times with different data sets under one method only.


Steps to write Parameterized JUnit:

-------------------------------------------

1) Identify the Input Data and Results

2) Create Fields in the test class.

3) Create a constructor.

4) Create a static method @Parameters

5) Create or Update the Test Method.

6) Mark the Test with @RunWith(Parameterized.class)


Q1) Which JUnit runner class should we use to run the parameterized test?

Ans:- Parameterized.class


Power Mock Jump Start:
------------------------------

Mockito Limitations:-
-----------------------------

1) Static

2) Final

3) Constructors

4) Private

5) Enums


PowerMock:-
------------------

1) It reuses what is already there in the Mocking frameworks like Mockito and EasyMock and extends them.

2) Mockit Etc uses Proxy Pattern.

3) It uses Bytecode Manipulation and Custom Class Loader to achieve what other Mocking frameworks can't do.

4) It has very similar syntax for Stubbing and Setting Expectations.

when thenReturn etc

Verifying

verify


5) PowerMock is a Mocking framework that allows you to mock out things that you cannot mock out things using Mockito and other Mocking frameworks.


Usecase:-
-------------

UserAdminService


UserDao-------------> final IDGenerator




create(User user) ------------------->  static final generateId



JUnit Spring Boot Project:
-------------------------------

Steps:
-------

1) Create the Project

2) Create the Model and Repository

3) Create the REST Controller

4) Configure the datasource

5) Test


Dependencies Used:-
----------------------------

1) spring-web

2) spring-data-jpa

3) mysql-connector-java

4) mockito-all


Eclipse plugin installer:
----------------------------

Lombok - https://projectlombok.org/p2


Quiz:
--------

Q1) While unit testing we test the private methods only?

Ans:- False


Q2) While unit testing we test the application end to end?

Ans:- False


Q3) What are the advantages of Unit Testing?

Ans:- 1. Improve Quality

         2. They run fast

         3. They become a regression suite


Q4) JUnit provides the mocking API?

Ans:- False


Q5) JUnit 4 test methods should follow certain naming conventions ?

Ans:- False


Q6) Which annotation can be used to setup data for each test method?

Ans:- @Before


Q7) Which assertion can we use to compare and see if the expected and actual values are equal?

Ans:- assertEquals


Q8) Which of the following is the default JUnit test runner?

Ans:- BlockJunit4Runner.class


Q9) Which JUnit annotation should be used to mark each test method?

Ans:- @Test


Q10) We use the @Expected annotation to assert exceptions?

Ans:- False


Q11) The methods marked with @Before run once for the entire test class?

Ans:- False


Q12) What is the first step in mocking?

Ans:- Stubbing and setting expectations


Q13) The assumption of mocking is that each Unit is tested in ?

Ans:- Isolation


Q14) Which annotation can be used to mock an object?

Ans:- @Mock


Q15) Which method in the Mockito API should be called to initialize the mocks?

Ans:- initMocks


Q16) Which static method can be used to stub out the method calls on a mocked object?

Ans:- when


Q17) While using  the when method to stub which method should be used return a value?

Ans:- thenReturn


Q18) Which methods in the JUnit API can be used to verify the results?

Ans:- assert methods


Q19) Code Coverage applies only for Conditional Statements and Loops?

Ans:- False


Q20) Which of the following is not a code coverage tool?

Ans:- Mockito


Q21) Parameterized JUnit tests were introduced in which version of JUnit?

Ans:- 4


Q22) Mockito can not mock static methods?

Ans:- True


Q23) PowerMock uses the proxy pattern to mock static method?

Ans:- False


0 Comments