0% found this document useful (0 votes)
20 views15 pages

Day-4-Sw Dev Tools

The document provides an overview of using Maven and JUnit 5 for unit and integration testing, including commands for creating a Maven project and managing dependencies. It details JUnit 5 features such as annotations, assertions, and mocking with Mockito, along with examples of test cases and configurations in pom.xml. Additionally, it covers concepts like parameterized tests, test ordering, and the use of tags for filtering test execution.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views15 pages

Day-4-Sw Dev Tools

The document provides an overview of using Maven and JUnit 5 for unit and integration testing, including commands for creating a Maven project and managing dependencies. It details JUnit 5 features such as annotations, assertions, and mocking with Mockito, along with examples of test cases and configurations in pom.xml. Additionally, it covers concepts like parameterized tests, test ordering, and the use of tags for filtering test execution.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 15

maven lab:

-------------
mvn --version

jar-> gav
Group id, Artifact, Version coordinate.”

mvn archetype:generate

maven life cycle


----------------------
clean default site
mvn compile
mvn package
mvn install

mvn package -DskipTests

junit and mockito


---------------------
https://www.guru99.com/software-testing.html

now we should create a maven project and run hello world of junit

junit 5: fundamentals:
_______________________
Unit testing:
_____________
where any given test covers the smallest unit of a program (a function or
procedure).
It may or may not take some input parameters and may or may not return some
values.

Integration testing:
___________________
where individual units are tested together to check whether all the
units interact with each other as expected.

To define one Test case we should use


a. JUnit 5 Annotations
b. JUnit 5 Assert API

=> Here, JUnit Runtime is provided with 3 components and one platform runtime.
i. JUnit Jupiter Engine (JUnit 5 API)
ii. JUnit Vintage Engine (JUnit 4 and 3 APIs)
iii. Integration (TestNg, Mock...etc)
maven dependencies:
-------------------------

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.21.0</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>2.23.0</version>
<scope>test</scope>
</dependency>

Some imp Junit 5 annotations


______________________________
@Test
@DisplayName
@BeforeEach
@AfterEach
@BeforeAl
@AfterAll
@Disable
@TestMethodOrder
@RepeatTest
@Tag
@ParameterizedTest
....
....

Demo:

@BeforeEach : To execute any logic once per test method before starting test
method.
@AfterEach : To execute any logic once per test method after finishing test
method.
@BeforeAll : To execute any logic once per test case before starting.
@AfterAll : To execute any logic once per test case after finishing.

Calculator application test:


---------------------------
public class CalculatorTest {

private Calculator calculator;

@BeforeEach
public void before(){
calculator=new Calculator();
}
@Test
public void addTest(){
assertThrows
(ArithmeticException.class, ()-> calculator.divide(4,0),"divide by
zero");
}

@Test
public void multiplyTest(){
assertEquals(18, calculator.multiply(9,2));
}

@Test
public void divideTest(){
assertEquals(3, calculator.divide(9,3));
}

@AfterEach
public void after(){
calculator=null;
}
}

Demo @Order
____________

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class EmployeeAppTest {

@EnabledOnOs(OS.LINUX)
@EnabledOnJre(JRE.JAVA_15)
@DisplayName("test for add employee")
@Order(value = 1)
@Test
public void addEmployee(){
System.out.println("testing add employee");
}
}

Demo @TestMethodOrder:
_____________________
@TestMethodOrder : We can define multiple test methods inside Testcase.
Those are executed in Random order by default.

We can specify our own order using @TestMethodOrder + OrderAnnotation


Here we need to provide @Order(number).

@TestMethodOrder(OrderAnnotation.class)
public class TestEmployee {

@Order(value = 1)
@Test
public void testSave() {
System.out.println("saving");
}

We can use @TestMethodOrder(Alphanumeric.class) for provide test method order.


First sort using 0-9 if same found then compare with A-Z sorting order.

@DisplayName : This annotation is used to provide 'Readable text' inplace of


actual method and class names at JUnit console.

Eg:
DisplayName("test for employee dao")
public class TestEmployee {

@DisplayName("test for saving employee dao")


@Test
public void testSave() {
System.out.println("saving");
}
//

Injecting TestInfo to get valuable informations


________________________________________________

To know our Test case details like classname,method name, display name,tag
name etc
we can use one interface TestInfo.

public class TestEmployee {

@DisplayName("test for saving employee dao")

@Test
public void testSave(TestInfo info) {
System.out.println(info.getTestMethod().toString());
System.out.println("saving");
}
}

@Disabled : This annotation is used to specify Ignore one Test-method


while executing test-case (do not execute test method)

@RepeatedTest
______________
=> To execute any test method multiple time (like batch processing) using
@RepeatedTest annotation.

public class TestEmployee {

@RepeatedTest(value = 3)
@Test
public void testUpdate() {
System.out.println("updating ");
}

Ex:
@DisplayName("TESTING EMPLOYEE TASK")
public class TestEmployee {

@RepeatedTest(value = 3,name="{displayName} -
{currentRepetition}/{totalRepetitions}")
@DisplayName("MULTIPLE TEST")
public void testMultiple(TestInfo info) {
//System.out.println("HELLO:"+info.getTestClass().get().getName());
//System.out.println("HELLO:"+info.getTestMethod().get().getName());
System.out.println("HELLO:"+info.getDisplayName());
}

@Tag
________

These are used to filter test methods for execution in different


environments.

For Example, i want to test export example in production env at same


i want to test delete operation only in development environment
then use tag concept and maven-surefire-plugin in pom.xml

@DisplayName("test for employee dao")


public class TestEmployee {

@DisplayName("test for saving employee dao")

@Test
public void testSave(TestInfo info) {
System.out.println(info.getTestMethod().toString());
System.out.println("saving");
}
@Tag(value = "dev")
@Test
public void testUpdate() {
System.out.println("updating ");
}

@Tag(value = "prod")
@Test
public void testDelete() {
System.out.println("deleting");
}
}

pom.xml
___________
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>int.nit</groupId>
<artifactId>JUnit5App</artifactId>
<version>1.0</version>

<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<!-- include tags -->
<groups>prod</groups>
<!-- exclude tags -->
<excludedGroups>dev</excludedGroups>
</configuration>
</plugin>
</plugins>
</build>

</project>

https://mkyong.com/junit5/junit-5-tagging-and-filtering-tag-examples/
AssertEquals() methods
_______________________
https://junit.org/junit5/docs/5.0.1/api/org/junit/jupiter/api/Assertions.html

Assert API :
___________

It is used to validate Test, IS CURRENT TEST PASS/FAIL?


Expected Value is compared with Actual Result.

=> JUnit 5 has provided class : Assertions (org.junit.jupiter.api)


which contains all static method "assert methods".

=> assert methods are used to compare Expected values with Actual Result.
If matching TEST PASS, else TEST FAIL.

=> Ex assert method : assertEquals(expected, actual)


This method is used to compared expected value with actual value

*) assertNotNull() / assertNull()

assertNotNull(object):

This method is used to specify that given object is not a null value
it holds data some data, else TEST FAIL.

assertNull(object): it indicates given object is null, else TEST FAIL.

*) assertDoesNotThrow(Executable) :
This is used to specify that our method call is not throwing any exception,
else if it throwing then TEST FAIL.

*) assertSame(ob1,ob2): This method is used to test that GIVEN TWO REFERENCES are
POINTED TO ONE OBJECT?
If yes TEST PASS, else TEST FAIL.

Q) What is the diff b/w assertSame() and assertEquals()?


A) assertEquals () : compares two objects data
assertSame() : compares object references.

*) fail() : This is used for testing multiple conditions,


if they are not met Manually FAIL TEST CASE.

*) assertArrayEquals() :use this method to compare data of two arrays (expected,


actual)

assertArrayEquals(expected, actual,"Data may not be same in two


arrays!");

*)assertTrue()/assertFalse()
These methods are used to test one boolean condition/expression/value.

assertTrue(): boolean value is expected as TRUE, else TEST FAIL.


assertFalse(): boolean value is expected as FALSE, else TEST FAIL.

assertAll(Executable...) : This is used to group all asset test methods and execute
once.
If all are PASS then TEST IS PASS, If one FAIL then TEST IS FAIL.

assertAll(
()->{

},
()->{

},
()->{

}
);

@ParameterizedTest
___________________

@ParameterizedTest
@CsvFileSource(resources = "/data.csv", numLinesToSkip = 1)
void toUpperCase_ShouldGenerateTheExpectedUppercaseValueCSVFile(
String input, String expected) {
String actualValue = input.toUpperCase();
assertEquals(expected, actualValue);
}

input,expected
test,TEST
tEst,TEST
Java,JAVA

https://www.baeldung.com/parameterized-tests-junit-5

junit mock testing:


____________________

What is Mocking and When Does It Come into the Picture?


___________________________________________________

What if we want to test service layer without completion of dao layer?


What if we want to test one service which depend on an service available on
other application?

=> mockito used for mocking

getting started:
------------------
maven dependencies:
--------------------

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
</dependencies>

Why mockito?
-----------

public interface BookDao {


public List<String> getBooks();
}

public class BookDaoImpl implements BookDao {


@Override
public List<String> getBooks() {
return Arrays.asList("java","rich dad poor dad","java adv");
}
}

public interface BookService {


public List<String> getBooks(String subject);
}

public class BookServiceImpl implements BookService {


private BookDao bookDao;

public void setBookDao(BookDao bookDao) {


this.bookDao = bookDao;
}

@Override
public List<String> getBooks(String subject) {
return bookDao.getBooks().stream().filter(title ->
title.contains(subject)).collect(Collectors.toList());
}

}
import org.junit.Assert;

public class DemoTest {

@Test
public void getBookTest() {
BookDao dao=new BookDaoImpl();

BookServiceImpl bookService=new BookServiceImpl();


bookService.setBookDao(dao);
List<String> books=bookService.getBooks("java");
Assert.assertEquals(2, books.size());
}
}

Useful Snippets and References


Easier Static Imports

Window > Preferences > Java > Editor > Content Assist > Favorites

org.junit.Assert
org.mockito.BDDMockito
org.mockito.Mockito
org.hamcrest.Matchers
org.hamcrest.CoreMatchers

mockito hello world:


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

public class DemoTest {

@Test
public void getBookTest() {

BookDao dao=mock(BookDao.class);

List<String> allbooks=Arrays.asList("java","rich dad poor dad","java


adv");

when(dao.getBooks()).thenReturn(allbooks);

BookServiceImpl bookService=new BookServiceImpl();


bookService.setBookDao(dao);
List<String> books=bookService.getBooks("java");
Assert.assertEquals(2, books.size());
}
}
Improvement 1:
--------------

public class DemoTest2 {

BookDao dao = mock(BookDao.class);

BookServiceImpl bookService = new BookServiceImpl();

@Before
public void before() {
List<String> allbooks = Arrays.asList("java", "rich dad poor dad",
"java adv");

when(dao.getBooks()).thenReturn(allbooks);
BookDao dao = mock(BookDao.class);
}

@Test
public void getBookTest() {

bookService.setBookDao(dao);
List<String> books = bookService.getBooks("java");
Assert.assertEquals(2, books.size());
}
}

mockito with annotations:


----------------------
//@RunWith(MockitoJUnitRunner.class) this will work with junit 4
//https://stackoverflow.com/questions/40961057/how-to-use-mockito-with-junit5

@ExtendWith(MockitoExtension.class)
public class DemoTest2 {

@InjectMocks
BookServiceImpl bookService = new BookServiceImpl(); //even we dont need to
create object

@Mock
BookDao dao;

@Before
public void before() {
List<String> allbooks = Arrays.asList("java", "rich dad poor dad",
"java adv");

when(dao.getBooks()).thenReturn(allbooks);

@Test
public void getBookTest() {
bookService.setBookDao(dao);
List<String> books = bookService.getBooks("java");
Assert.assertEquals(2, books.size());
}
}

MockitoAnnotations.initMocks(this) vs @RunWith(MockitoJUnitRunner.class)

Note:
----
Mockito cannot mock or spy on Java constructs such as final classes and
methods, static methods, enums, private methods, the equals() and
hashCode() methods, primitive types, and anonymous classes

Partial Mocking: @Spy


--------------------
When we want an object in the test class to mock some method(s),
but also call some actual method(s), then we need partial mocking.
This is achieved via @Spy

Unlike using @Mock, with @Spy, a real object is created,


but the methods of that object can be mocked or can be actually called—
whatever we need.

Example:
--------
@Repository
public class BookDaoImpl implements BookDao {
@Override
public List<String> getBooks() {
log();
return null;
}

public void log() {


System.out.println("----------");
}
}

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {

@Spy
BookDaoImpl dao;

@InjectMocks
BookServiceImpl bookService;

// when tested log() method is going to be called.....

}
A few mockito examples mocking List class
-----------------------------------------

public class ListTest {

@Test
public void letsMockListSize() {
List list = mock(List.class);
Mockito.when(list.size()).thenReturn(10);
assertEquals(10, list.size());
}

@Test
public void letsMockListSizeWithMultipleReturnValues() {
List list = mock(List.class);
Mockito.when(list.size()).thenReturn(10).thenReturn(20);
assertEquals(10, list.size()); // First Call
assertEquals(20, list.size()); // Second Call
}

@Test
public void letsMockListGet() {
List<String> list = mock(List.class);
Mockito.when(list.get(0)).thenReturn("javatraining");
assertEquals("javatraining", list.get(0));
assertNull(list.get(1));
}

@Test
public void letsMockListGetWithAny() {
List<String> list = mock(List.class);
Mockito.when(list.get(Mockito.anyInt())).thenReturn("javatraining");
// If you are using argument matchers, all arguments
// have to be provided by matchers.
assertEquals("javatraining", list.get(0));
assertEquals("javatraining", list.get(1));
}

hello world unit testing spring mvc controller:


-----------------------------------
@Controller
public class Hello {
@GetMapping("/hello")
public String hello(ModelMap model) {
model.addAttribute("name", "hello world");
return "helloview";

}
}
public class HelloTest {

@InjectMocks
private Hello hello;

private MockMvc mockMvc;

@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(hello).build();
}

@Test
public void testCreateSignupFormInvalidUser() throws Exception {
this.mockMvc.perform(get("/hello")).andExpect(status().isOk());
}

https://www.toptal.com/java/unit-integration-junit-tests

Dependencies:
___________________
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.21.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>2.23.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.8.4</version>
<scope>test</scope>
</dependency>

</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<!-- include tags -->
<groups>prod</groups>
<!-- exclude tags -->
<excludedGroups>dev</excludedGroups>
</configuration>
</plugin>
</plugins>
</build>

log4j
---------

git
----

You might also like