0% found this document useful (0 votes)
45 views53 pages

JUnit Mockito

The document provides an overview of JUnit and Mockito, focusing on their functionalities for testing in Java. It covers JUnit's structure, including annotations, terminology, and how to write test classes, as well as Mockito's capabilities for mocking objects and verifying interactions. Key concepts such as test fixtures, assertions, and recommended testing approaches are also discussed.

Uploaded by

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

JUnit Mockito

The document provides an overview of JUnit and Mockito, focusing on their functionalities for testing in Java. It covers JUnit's structure, including annotations, terminology, and how to write test classes, as well as Mockito's capabilities for mocking objects and verifying interactions. Key concepts such as test fixtures, assertions, and recommended testing approaches are also discussed.

Uploaded by

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

JUnit + Mockito

Tin Bui Huy


Jan 2014
JUnit
 What is the JUnit?
 Terminology
 Available JUnit annotations
 Assert statements
 Once more, in pictures
 Writing a JUnit test class
 Recommended approach
JUnit
 What is the JUnit?
 Terminology
 Available JUnit annotations
 Assert statements
 Once more, in pictures
 Writing a JUnit test class
 Recommended approach
JUnit - What is the JUnit?
 JUnit is a framework for writing tests

 JUnit was written by


 Erich Gamma (of Design Patterns fame)
 and Kent Beck (creator of XP methodology)

 JUnit uses Java’s reflection capabilities


JUnit - What is the JUnit?
 JUnit helps the programmer:
 Define and execute tests and test suites
 Formalize requirements and clarify architecture
 Write and debug code
 Test source code automatically
 Integrate code and always be ready to release a
working version

 JUnit is not included in Sun’s SDK,


 But almost all IDEs include it
JUnit
 What is the JUnit?
 Terminology
 Available JUnit annotations
 Assert statements
 Once more, in pictures
 Writing a JUnit test class
 Recommended approach
JUnit - Terminology
 A test fixture sets up the data (both
objects and primitives) that are needed to
run tests
 Example: If you are testing code that updates
an employee record, you need an employee
record to test it on

 A unit test is a test of a single class

 A test case tests the response of a single


method to a particular set of inputs
JUnit - Terminology
 A test suite is a collection of test cases

 A test runner is software that runs tests


and reports results

 An integration test is a test of how well


classes work together
 JUnit provides some limited support for
integration tests
JUnit
 What is the JUnit?
 Terminology
 Available JUnit annotations
 Assert statements
 Once more, in pictures
 Writing a JUnit test class
 Recommended approach
Available JUnit annotations

The following table gives an overview of the available annotations in


JUnit 4.x.
Annotation Description
@Test The @Test annotation identifies a method
public void method() as a test method.
@Test (expected = Fails, if the method does not throw the
Exception.class) named exception.
@Test(timeout=100) Fails, if the method takes longer than 100
milliseconds.
@Before This method is executed before each test.
public void method() It is used to can prepare the test
environment (e.g. read input data,
initialize the class).
Available JUnit annotations
Annotation Description
@After This method is executed after each test. It is
public void method() used to cleanup the test environment (e.g.
delete temporary data, restore defaults). It can
also save memory by cleaning up expensive
memory structures.
@BeforeClass This method is executed once, before the start
public static void of all tests. It is used to perform time intensive
method() activities, for example to connect to a
database. Methods annotated with this
annotation need to be defined asstatic to work
with JUnit.
@AfterClass This method is executed once, after all tests
public static void have been finished. It is used to perform clean-
method() up activities, for example to disconnect from a
database. Methods annotated with this
annotation need to be defined as static to work
with JUnit.
@Ignore Ignores the test method. This is useful when
JUnit
 What is the JUnit?
 Terminology
 Available JUnit annotations
 Assert statements
 Once more, in pictures
 Writing a JUnit test class
 Recommended approach
Assert statements

Statement Description
fail(String) Let the method fail. Might be used to check
that a certain part of the code is not reached.
Or to have a failing test before the test code is
implemented. The String parameter is
optional.
assertTrue([message], Checks that the boolean condition is true.
boolean condition)

assertFalse([message], Checks that the boolean condition is false.


boolean condition)

assertEquals([String Tests that two values are the same.


message], expected, Note: for arrays the reference is checked not
actual) the content of the arrays.
Assert statements

Statement Description
assertEquals([String Test that float or double values match.
message], expected, The tolerance is the number of decimals which
actual, tolerance) must be the same.
assertNull([message], Checks that the object is null.
object)

assertNotNull([messag Checks that the object is not null.


e], object)

assertSame([String], Checks that both variables refer to the same


expected, actual) object.

assertNotSame([String Checks that both variables refer to different


], expected, actual) objects.
Assert statements

Note
You should provide meaningful messages in
assertions so that it is easier for the developer
to identify the problem.

This helps in fixing the issue, especially if


someone looks at the problem, which did not write
the code under test or the test code.
JUnit
 What is the JUnit?
 Terminology
 Available JUnit annotations
 Assert statements
 Once more, in pictures
 Writing a JUnit test class
 Recommended approach
Once more, in pictures

Test suite Test runner


Another unit test
Test case (for one method)  A unit test tests the
Another test case methods in a single class
 A test case tests (insofar as
Another unit test possible) a single method
Another test case
 You can have multiple test
cases for a single method
Another test case  A test suite combines unit
Another test case
tests
 The test fixture provides
Unit test (for one class) software support for all this
Test case (for one method)  The test runner runs unit
Another test case tests or an entire test suite
 Integration testing (testing
that it all works together) is
Test fixture not well supported by JUnit
JUnit
 What is the JUnit?
 Terminology
 Available JUnit annotations
 Assert statements
 Once more, in pictures
 Writing a JUnit test class
 Recommended approach
Writing a JUnit test class

Start by importing these JUnit 4 classes:


import org.junit.*;
import static org.junit.Assert.*; // note static
import

Declare your test class in the usual way


public class MyProgramTest {

}
Writing a JUnit test class

Declare an instance of the class being tested

You can declare other variables, but don’t


give them initial values here
public class MyProgramTest {
MyProgram program;
int someVariable;

}
Writing a JUnit test class

Define a method (or several methods) to be


executed before each test

Initialize your variables in this method, so


that each test starts with a fresh set of
values
@Before
public void setUp() {
program = new MyProgram();
someVariable = 1000;
}
Writing a JUnit test class, II

You can define one or more methods to be


executed after each test

Typically such methods release resources,


such as files
Usually there is no need to bother with this
method
@After
public void tearDown() {
}
A simple example
Suppose you have a class Arithmetic with methods int
multiply(int x, int y), and boolean isPositive(int x)

import org.junit.*;
import static org.junit.Assert.*;

public class ArithmeticTest {


 @Test
public void testMultiply() {
assertEquals(4, Arithmetic.multiply(2, 2));
assertEquals(-15, Arithmetic.multiply(3, -5));
}

 @Test
public void testIsPositive() {
assertTrue(Arithmetic.isPositive(5));
assertFalse(Arithmetic.isPositive(-5));
assertFalse(Arithmetic.isPositive(0));
}

}
Writing a JUnit test class

This page is really only for expensive setup,


such as when you need to connect to a
database to do your testing

If you wish, you can declare one method to be


executed just once, when the class is first
loaded
@BeforeClass
public static void setUpClass() throws Exception
{
// one-time initialization code
}
Writing a JUnit test class

If you wish, you can declare one method to


be executed just once, to do cleanup after
all the tests have been completed
@AfterClass
public static void tearDownClass() throws
Exception {
// one-time cleanup code
}
Special features of @Test

You can limit how long a method is allowed to


take

This is good protection against infinite loops

The time limit is specified in milliseconds

The test fails if the method takes too long


@Test (timeout=10)
public void greatBig() {
assertTrue(program.ackerman(5, 5) >
10e12);
}
Special features of @Test

Some method calls should throw an


exception

You can specify that a particular exception


is expected

The test will pass if the expected exception


is thrown, and fail otherwise
@Test (expected=IllegalArgumentException.class)
public void factorial() {
program.factorial(-5);
}
Ignoring a test

The @Ignore annotation says to not run a test

@Ignore("I don’t want Dave to know this doesn’t work")


@Test
public void add() {
assertEquals(4, program.sum(2, 2));
}

You shouldn’t use @Ignore without a very good


reason!

@Ignore can be used for class to ignore the whole


test class
Test suites

You can define a suite of tests


@RunWith(value=Suite.class)
@SuiteClasses(value={
MyProgramTest.class,
AnotherTest.class,
YetAnotherTest.class
})
public class AllTests {
}
JUnit
 What is the JUnit?
 Terminology
 Available JUnit annotations
 Assert statements
 Once more, in pictures
 Writing a JUnit test class
 Recommended approach
Recommended approach

 Write a test for some method you intend to


write
 If the method is fairly complex, test only the
simplest case

 Write a stub for the method

 Run the test and make sure it fails


Recommended approach

 Replace the stub with code


 Write just enough code to pass the tests

 Run the test


 If it fails, debug the method (or maybe debug the
test); repeat until the test passes

 If the method needs to do more, or handle


more complex situations, add the tests for
these first, and go back to step 3
Mockito

Mockito for mocking objects


Using Mockito

Limitations

Configuring the mock objects

Verify the calls on the mock objects

Spy
Mockito

Mockito for mocking objects


Using Mockito

Limitations

Configuring the mock objects

Verify the calls on the mock objects

Spy
Mockito for mocking objects

Mockito is a popular mock framework which


can be used in conjunction with JUnit.

Mockito allows you to create and configure


mock objects.
Mockito

Mockito for mocking objects


Using Mockito

Limitations

Configuring the mock objects

Verify the calls on the mock objects

Spy
Using Mockito

Mockito supports the creation of mock objects


with the static mock() method call.

It also supports the creation of mock objects


based on the @Mock annotation.
Using Mockito

If you use annotations, you must initialize this


mock objects with
aMockitoAnnotations.initMocks(this) method
call.
Using Mockito
Mockito

Mockito for mocking objects


Using Mockito

Limitations

Configuring the mock objects

Verify the calls on the mock objects

Spy
Limitations

 Mockito has certain limitations. It can not


test the following constructs:
 Final classes
 Anonymous classes
 Primitive types
Mockito

Mockito for mocking objects


Using Mockito

Limitations

Configuring the mock objects

Verify the calls on the mock objects

Spy
Configuring the mock objects

 Mockito has a fluent API. You can use


the verify() method to ensure that a method
was called.

 when(....).thenReturn(....) can be used to


specify a condition and a return value for
this condition.

 doReturn(object).when(kdskfsk).methodCall

works similar.
Configuring the mock objects

@Test
public void test1 ( ) {

MyClass test =
Mockito.mock(MyClass.class);

// Define return value for method getUniqueId( )

test.when(test.getUniqueId( )).thenReturn(43)
;

// TODO use mock in test…


}
Mockito

Mockito for mocking objects


Using Mockito

Limitations

Configuring the mock objects

Verify the calls on the mock objects

Spy
Verify the calls on the mock
objects
@Test
public void test1 ( ) {
MyClass test = Mockito.mock(MyClass.class);

// Define return value for method getUniqueId( )

test.when(test.getUniqueId( )).thenReturn(43);

// TODO use mock in test…

// Now check if method testing was called with the


parameter 12
Mockito.verify(test).testing(Matchers.eq(12));

// Was the method called twice?


Verify the calls on the mock
objects

Note
This kind of testing is sometimes
called behavior testing, because it does not
check the result of a method call, but it checks
that a method is called with the right parameters.
Mockito

Mockito for mocking objects


Using Mockito

Limitations

Configuring the mock objects

Verify the calls on the mock objects

Spy
Spy
@Spy or the spy() method can be used to wrap a
real object. Every call, unless specified otherwise, is
delegated to the object.
// Lets mock a LinkedList
List list = new LinkedList( );
List spy = spy(list);

// You have to use doReturn( ) for stubbing


doReturn(“foo”).when(spy).get(0);

// This would not work


// Real method is called so spy.get(0)
// Throws IndexOutOfBoundsException (list is still empty)
when(spy.get(0)).thenReturn(“foo”);
Spy
The verifyNoMoreInteractions() allows you
to check that no other method was called.

You also have the @InjectMocks annotation


which tries to do constructor dependency
injection based on the type.

The following code is a slightly modified


example from the Javadoc.
Spy
public class ArticleManagerTest {
@Mock
private ArticleCalculator calculator;
@Mock
private ArticleDatabase database;
@Spy
private UserProvider userProvider = new
ConsumerUserProvider( );

// Creates instance of ArticleManager


// and performs constructor injection on it
@InjectMocks
private ArticleManager manager = new
ArticleManager( );

@Test
public void shouldDoSomething( ) {
MokitoAnnotations. initMocks(this);
verify(database).
Q/A
Thank you!

You might also like