Day-4-Sw Dev Tools
Day-4-Sw Dev Tools
-------------
mvn --version
jar-> gav
Group id, Artifact, Version coordinate.”
mvn archetype:generate
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.
=> 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>
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.
@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.
@TestMethodOrder(OrderAnnotation.class)
public class TestEmployee {
@Order(value = 1)
@Test
public void testSave() {
System.out.println("saving");
}
Eg:
DisplayName("test for employee dao")
public class TestEmployee {
To know our Test case details like classname,method name, display name,tag
name etc
we can use one interface TestInfo.
@Test
public void testSave(TestInfo info) {
System.out.println(info.getTestMethod().toString());
System.out.println("saving");
}
}
@RepeatedTest
______________
=> To execute any test method multiple time (like batch processing) using
@RepeatedTest annotation.
@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
________
@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 :
___________
=> assert methods are used to compare Expected values with Actual Result.
If matching TEST PASS, else TEST FAIL.
*) 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.
*) 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.
*)assertTrue()/assertFalse()
These methods are used to test one boolean condition/expression/value.
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
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?
-----------
@Override
public List<String> getBooks(String subject) {
return bookDao.getBooks().stream().filter(title ->
title.contains(subject)).collect(Collectors.toList());
}
}
import org.junit.Assert;
@Test
public void getBookTest() {
BookDao dao=new BookDaoImpl();
Window > Preferences > Java > Editor > Content Assist > Favorites
org.junit.Assert
org.mockito.BDDMockito
org.mockito.Mockito
org.hamcrest.Matchers
org.hamcrest.CoreMatchers
@Test
public void getBookTest() {
BookDao dao=mock(BookDao.class);
when(dao.getBooks()).thenReturn(allbooks);
@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());
}
}
@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
Example:
--------
@Repository
public class BookDaoImpl implements BookDao {
@Override
public List<String> getBooks() {
log();
return null;
}
@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
@Spy
BookDaoImpl dao;
@InjectMocks
BookServiceImpl bookService;
}
A few mockito examples mocking List class
-----------------------------------------
@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));
}
}
}
public class HelloTest {
@InjectMocks
private Hello hello;
@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
----