July /16th/2018
________________________________________________________________________________________________________________________
TestNG :
http://websystique.com/java/testng-tutorial/
Difference between Junit and Test NG
https://www.guru99.com/junit-vs-testng.html
Difference between @mock and @injectMock
https://stackoverflow.com/questions/16467685/difference-between-mock-and-injectmocks
Difference between @mock and @spy or When to use mock & when to use spy
https://stackoverflow.com/questions/12827580/mocking-vs-spying-in-mocking-frameworks
http://www.javainuse.com/java/mockthenCallRealMethod
https://dzone.com/articles/mockito-mock-vs-spy-in-spring-boot-tests
https://javapointers.com/tutorial/difference-between-spy-and-mock-in-mockito/
https://stackoverflow.com/questions/16467685/difference-between-mock-and-injectmocks
_________________________________________________________________________
DBUnit :
https://stackoverflow.com/questions/3950002/is-there-a-dbunit-like-framework-that-doesnt-suck-for-java-scala
https://opensourceforu.com/2011/05/testing-your-databases-with-dbunit/
http://dbunit.sourceforge.net/howto.html
Note that none
https://dzone.com/articles/mockito-dbunit-implementingFlyway annotation
https://github.com/flyway/flyway-test-extensions/wiki/Usage-flyway-dbunit-test
http://dbunit.sourceforge.net/howto.html
https://examples.javacodegeeks.com/core-java/junit/junit-dbunit-example/
https://www.marcphilipp.de/blog/2012/03/13/database-tests-with-dbunit-part-1/
https://opensourceforu.com/2011/05/testing-your-databases-with-dbunit/
http://websystique.com/java/testng-tutorial/
__________________________________________________________________________
Testing :Spring Mockito:
Spring Mockito :
Configure simple return behavior for mock MyList listMock = Mockito.mock(MyList.class);
when(listMock.add("aaa")).thenReturn(false); boolean added = listMock.add(randomAlphabetic(6)); assertThat(added, is(false));
Configure return behavior for mock in 
an alternative way
doReturn(false).when(listMock).add("aaa"; boolean added = listMock.add(randomAlphabetic(6)); assertThat(added, is(false));
Configure mock to throw an exception on
a method call @Test(expected = IllegalStateException.class) public void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() { when(listMock.add("aaa")).thenThrow(IllegalStateException.class); listMock.add(randomAlphabetic(6)); }
when(listMock.add("aaa")).theThrow(IllegalStateException.class)
Configure the behavior of a method with void
return type – to throw an exception
MyList listMock = Mockito.mock(MyList.class); doThrow(NullPointerException.class).when(listMock).clear(); listMock.clear();
Configure the behavior of multiple calls MyList listMock = Mockito.mock(MyList.class); when(listMock.add("aaa")) .thenReturn(false) .thenThrow(IllegalStateException.class); listMock.add(randomAlphabetic(6)); listMock.add(randomAlphabetic(6)); // will throw the exception
Configure the behavior of a spy MyList instance = new MyList(); MyList spy = Mockito.spy(instance); doThrow(NullPointerException.class).when(spy).size(); spy.size(); // will throw the exception
doThrow(NPE.class).when()
Configure method to call the real, underlying
method on a mock when(listMock.size()).thenCallRealMethod(); assertThat(listMock.size(), equalTo(1));
configure mock method call with custom Answer MyList listMock = Mockito.mock(MyList.class); doAnswer(invocation -> "Always the same").when(listMock).get(anyInt()); String element = listMock.get(1); assertThat(element, is(equalTo("Always the same")));
verify simple invocation on mock ListmockedList = mock(MyList. class); mockedList.size(); verify(mockedList).size();
verify number of interactions with mock mockedList.size(); verify(mockedList, times(1)).size();
verify no interaction with the whole mock occurred ListmockedList = mock(MyList. class); verifyZeroInteractions(mockedList);
verify no interaction with a specific method occurred ListmockedList = mock(MyList. class); verify(mockedList, times(0)).size();
verify there are no unexpected interactions – this should fail: ListmockedList = mock(MyList. class); mockedList.size(); mockedList.clear(); verify(mockedList).size(); verifyNoMoreInteractions(mockedList);
verify order of interactions ListmockedList = mock(MyList. class); mockedList.size(); mockedList.add("a parameter"); mockedList.clear(); InOrder inOrder = Mockito.inOrder(mockedList); inOrder.verify(mockedList).size(); inOrder.verify(mockedList).add("a parameter"); inOrder.verify(mockedList).clear();
verify an interaction has not occurred ListmockedList = mock(MyList. class); mockedList.size(); verify(mockedList, never()).clear();
verify an interaction has occurred at least certain number of times ListmockedList = mock(MyList. class); mockedList.clear(); mockedList.clear(); mockedList.clear(); verify(mockedList, atLeast(1)).clear(); verify(mockedList, atMost(10)).clear(); verify interaction with exact argument ListmockedList = mock(MyList. class); mockedList.add("test"); verify(mockedList).add("test");
verify interaction with flexible/any argument ListmockedList = mock(MyList. class); mockedList.add("test"); verify(mockedList).add("test");
verify interaction using argument capture ListmockedList = mock(MyList. class); mockedList.addAll(Lists.newArrayList("someElement") ); ArgumentCaptorargumentCaptor = ArgumentCaptor.
forClass(List.class); verify(mockedList).addAll(argumentCaptor.capture()); ListcapturedArgument = argumentCaptor. capturedArgument, hasItem("someElement"));> getValue(); assertThat(
Hammerst
| 
5.How
  are mocking framework do that   ? | 
| 
They
  provide 5 types of objects they are called test doubles: 
ü 
  Dummy
  objects:  just created  to pass around ,are not used 
ü 
  Mocking
  objects: dummy implementation of 
  interface or class 
ü 
  Fake
  objects: similar to real object but simpler implementation | 
| 
How
  will you mock objects? | 
| 
There are two
  ways to do this: | 
| 
Annotate the
  class @RunsWith(MockitoJunitRunner.class) 
& use  
@mock  MyClass myClass; 
or  
mockedmyclass = mock(Myclass.class); | 
| 
@Rule 
MockitoRule mockitoRule –
  MockitoJunit.rule(); 
@Rule public MockitoRule rule =
  MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); 
@mock  MyClass myClass; 
MessagetUtils msg
  = new MessageUtils(myClass); 
----------------------------------------------------------- 
MessgaeUtils msg
  = mock(mockedMyClass); | 
| 
5.How
  will configure mockito ? | ||||
| 
Step1:
  Either of the 2 
Tell the
  framework that you are using mockito  
a)@RunsWith(MockitoRunner.class) 
or 
b)MockitAnnotations.initMocks(this) | ||||
| 
     Step 2// use @Mock over the object that
  you intend to mock 
     @Mock  
private AsynchronousSocketChannel channel; 
or  
    final Future | ||||
| 
When thenReturn
  expression 
Sets a generic Answer for the method. This method is an alias of thenAnswer(Answer). This alias allows more readable tests on
  occasion, for example: 
 //using 'then' alias: 
 when(mock.foo()).then(returnCoolValue()); 
 //versus good old 'thenAnswer: 
 when(mock.foo()).thenAnswer(byReturningCoolValue()); | ||||
| 
//when  thenReturn 
Sets a return value to be returned when the method is
  called. E.g: 
 when(mock.someMethod()).thenReturn(10); 
Parameters: 
value return value 
Returns: 
iOngoingStubbing object that allows stubbing
  consecutive calls | ||||
| 
//when  thenReturn 
Sets a return value to be returned when the method is
  called. E.g: 
 when(mock.someMethod()).thenReturn(10); 
Parameters: 
value return value 
Returns: 
iOngoingStubbing object that allows stubbing
  consecutive calls | ||||
| 
When
  thenCallRealMethods expression 
Sets the real implementation to be called when the
  method is called on  
   when(mock.someMethod()).thenCallRealMethod(); 
   // calls real method: 
   mock.someMethod(); | ||||
| 
When thenThrow expression 
Sets Throwable classes to be thrown when the method is
  called. E.g: 
 when(mock.someMethod()).thenThrow(RuntimeException.class); | ||||
| 
“doReturn when and doThrow when” 
NOTE: The  doReturn(…).when(…).methodCallcall chain works similar towhen(….).thenReturn(….). It is useful for mocking methods which give an exception
  during a call, e.g., if you use use functionality like Wrapping
  Java objects with Spy.
Properties
  properties = new Properties(); 
Properties spyProperties = spy(properties); 
doReturn(“42”).when(spyProperties).get(”shoeSize”); 
String value =
  spyProperties.get(”shoeSize”); 
assertEquals(”42”,
  value); | ||||
| 
Question:How will you mock a linked list or hashmap? 
Answer:  
 | 
| 
6.Example
  of Mockito | 
| 
@BeforeClass 
public static void setUp(){ 
    mockedBookDAL = mock(BookDAL.class); 
    book1 = new Book("8131721019","Compilers Principles",Arrays.asList("D.
  Jeffrey Ulman","Ravi Sethi", "Alfred V. Aho", "Monica S. Lam"), 
            "Pearson Education Singapore Pte Ltd", 2008,1009,"BOOK_IMAGE"); 
    book2 = new Book("9788183331630","Let Us C 13th Edition", 
            Arrays.asList("Yashavant Kanetkar"),"BPB PUBLICATIONS", 2012,675,"BOOK_IMAGE"); 
    when(mockedBookDAL.getAllBooks()).thenReturn(Arrays.asList(book1, book2)); 
    when(mockedBookDAL.getBook("8131721019")).thenReturn(book1); 
    when(mockedBookDAL.addBook(book1)).thenReturn(book1.getIsbn()); 
    when(mockedBookDAL.updateBook(book1)).thenReturn(book1.getIsbn()); 
  } | 
| 
@Rule | 
@Rule 
     public MockitoRule mockitoRule = new MockitoRule(this); 
     @Rule 
     public ExpectedException thrown = ExpectedException.none(); 
@Rule public
  MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); | 
| 
@Mock | |
| 
When  
thenReturn | 
when(mockEcho.echo(anyString())) 
                                      .thenReturn(echoResponse("0001")); 
assertEquals(echoResponse("0001"), mockEcho.echo("Any
  String")); | 
| 
When thenThrow | |
| 
When thenCallrealmethod | |
| 
When then | |
| 
5.How
  do verify a call? | 
| 
//create and configure mock 
1.Myclass myClass = new Mockito.mock(MyClass.class); 
When(myClass.getId()).thenReturn(43) 
         2. 
  Myclass myclass = mock(MyClass.class); 
           When(myClass.getUniqueId()).then(); 
      3. @Mock Myclass  myclass; | 
| 
This
  tests if the method tested was actually tested with argument 43 
1.Verify(myclass).testing(ArgumentMachters.eq(12)); | 
| 
2.verify(myclass,never).somemethod(“never called”) | 
| 3. verify(myClass, atLeastOnce()).someMethod("called at least once"); | 
| 
verify(test, atLeast(2)).someMethod("called at least twice"); | 
| 
verify(test, times(5)).someMethod("called five times"); | 
| 
 
  verify(test, atMost(3)).someMethod("called at most 3 times"); | 
| 
In case you do
  not care about the value, use the anyX, e.g., anyInt, anyString(), or any(YourClass.class)methods. | 
| 
Verify(myclass,anyString()).somemethod(“here I am”) | 
| 
6.How
  to inject dependency in via Mockito ? | 
| 
@injectMocks | 
| 
@RunWith(MockitoJUnitRunner.class) 
public class ArticleManagerTest  { 
      
  @Mock ArticleCalculator calculator; 
      
  @Mock ArticleDatabase database; 
      
  @Mock User user; 
      
  @Spy private UserProvider
  userProvider = new ConsumerUserProvider(); 
      
  @InjectMocks
  private ArticleManager manager;  
      
  @Test public void shouldDoSomething() { 
          
  // calls addListener with an instance of ArticleListener 
          
  manager.initialize(); 
          
  // validate that addListener was called 
          
  verify(database).addListener(any(ArticleListener.class)); 
      
  } 
} | 
| 
7.What
  is ArgumentCaptor ? | 
| 
The ArgumentCaptor class
  allows to access the arguments of method calls
  during verification. This allows to capture these argument of method 
@Rule 
public MockitRule  rule = MockitRule().rule(); 
@Captor 
private
  ArgumentCaptor 
 
@Test 
    public final void
  shouldContainCertainListItem() { 
        List 
        final List 
       
  mockedList.addAll(asList); 
        verify(mockedList).addAll(captor.capture()); 
        final List 
        assertThat(capturedArgument,
  hasItem("someElement")); 
    } | 
| 
8.How
  to deal with complex objects ? | 
| 
Using
   doAnswers ….when 
When
  …… then Answer 
It is possible to define a Answer object for complex results. While thenReturn returns a predefined value every time, with answers you can calculate a response based on
  the arguments given to your stubbed method. This can be useful if your stubbed method is
  supposed to call a function on one of the arguments or if your method is
  supposed to return the first argument to allow method chaining. There
  exists a static method for the latter. Also note that there a different ways
  to configure an answer: 
@Test public final void
  answerTest() {     // with doAnswer():     doAnswer(returnsFirstArg()).when(list).add(anyString());     // with
  thenAnswer():    
  when(list.add(anyString())).thenAnswer(returnsFirstArg());     // with
  then() alias:    
  when(list.add(anyString())).then(returnsFirstArg()); } | 
| 
9.How
  to deal with complex objects when you need a call back ? | 
| 
@Test 
public final void callbackTest() { 
   
  ApiService service = mock(ApiService.class); 
   
  when(service.login(any(Callback.class))).thenAnswer(i -> { 
       
  Callback callback =
  i.getArgument(0); 
        callback.notify("Success"); 
        return null; 
   
  }); 
} | 
| 
10.How
  will you mock a final class? | 
| 
final
  class FinalClass { 
    public final String finalMethod() {
  return "something"; } 
} 
@Test 
public
  final void mockFinalClassTest() { 
     FinalClass instance = new FinalClass(); 
     FinalClass mock =
  mock(FinalClass.class); 
     when(mock.finalMethod()).thenReturn("that other thing"); 
     assertNotEquals(mock.finalMethod(),
  instance.finalMethod()); 
} | 
| 
11.What
  is mockito strict rule ? | 
| 
// activate the strict subs rule 
@Rule public
  MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); 
@Test 
public void withStrictStubsTest() throws Exception
  { 
   
  DeepThought deepThought = mock(DeepThought.class); 
    when(deepThought.getAnswerFor("Ultimate Question of Life, The Universe,
  and Everything")).thenReturn(42); 
    // this fails now with an
  UnnecessaryStubbingException since it is never called in the test 
   
  when(deepThought.otherMethod("some mundane
  thing")).thenReturn(null); 
    // this will now throw a
  PotentialStubbingProblem Exception since we usually don't want to call
  methods on mocks without configured behavior 
    deepThought.someMethod(); 
   
  assertEquals(42, deepThought.getAnswerFor("Ultimate Question of
  Life, The Universe, and Everything")); 
    // verifyNoMoreInteractions now
  automatically verifies that all stubbed methods have been called as well 
   
  verifyNoMoreInteractions(deepThought); 
} | 
| 
What
  are the limitations of mockito ? | 
| 
Mockito has certain limitations. For example, you cannot mock static methods and private methods. | 
| 
Initializing
  MOCKITO Framework | 
| 
//1.
  Initialize 
@RunWith(MockitoJUnitRunner.class) 
public class MockitoAnnotationTest { 
    ... 
} 
or  
@Before 
public void init() { 
    MockitoAnnotations.initMocks(this); 
} | 
| 
@Mock
  Annotations | 
| 
@Test 
public void whenNotUseMockAnnotation_thenCorrect() { 
    List mockList = Mockito.mock(ArrayList.class); 
    mockList.add("one"); 
    Mockito.verify(mockList).add("one"); 
    assertEquals(0, mockList.size()); 
    Mockito.when(mockList.size()).thenReturn(100); 
    assertEquals(100, mockList.size()); 
} | 
| 
@Mock 
List 
@Test 
public void whenUseMockAnnotation_thenMockIsInjected() { 
    mockedList.add("one"); 
    Mockito.verify(mockedList).add("one"); 
    assertEquals(0, mockedList.size()); 
    Mockito.when(mockedList.size()).thenReturn(100); 
    assertEquals(100, mockedList.size()); 
} | 
| 
@spy Annotations | |
| 
 | |
| 
@Spy 
List 
@Test 
public void whenUseSpyAnnotation_thenSpyIsInjected() { 
    spiedList.add("one"); 
    spiedList.add("two"); 
    Mockito.verify(spiedList).add("one"); 
    Mockito.verify(spiedList).add("two"); 
    assertEquals(2, spiedList.size()); 
    Mockito.doReturn(100).when(spiedList).size(); 
    assertEquals(100, spiedList.size()); 
} | 
| 
@Captor
  Annotations --ArgumentCaptor instance | ||
| 
 | ||
| 
@Mock 
List
  mockedList; 
@Captor 
ArgumentCaptor
  argCaptor; 
@Test 
public void whenUseCaptorAnnotation_thenTheSam() { 
    mockedList.add("one"); 
    Mockito.verify(mockedList).add(argCaptor.capture()); 
    assertEquals("one", argCaptor.getValue()); 
} | 
| 
@InjectMocks | 
| 
@Mock 
Map 
@InjectMocks 
MyDictionary
  dic = new MyDictionary(); 
@Test 
public void whenUseInjectMocksAnnotation_thenCorrect() { 
    Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning"); 
    assertEquals("aMeaning",
  dic.getMeaning("aWord")); 
} | 
| 
public class MyDictionary { 
    Map 
    public MyDictionary() { 
        wordMap = new HashMap 
    } 
    public void add(final String word, final String meaning) { 
        wordMap.put(word, meaning); 
    } 
    public String getMeaning(final String word) { 
        return wordMap.get(word); 
    } 
} | 
| 
http://www.baeldung.com/mockito-annotations | 
| 
When Mockito creates a mock – it does so
  from the Class of an Type, not from an actual instance. The mock simply creates a
  bare-bones shell instance of the Class, entirely instrumented to track
  interactions with it. 
@Test 
public void whenCreateMock_thenCreated() { 
    List mockedList = Mockito.mock(ArrayList.class); 
    mockedList.add("one"); 
    Mockito.verify(mockedList).add("one"); 
    assertEquals(0, mockedList.size()); 
} | 
| 
A spy on the other hand will behave
  differently – it will
  actually call the real implementation of the add method and add the element
  to the underlying list: 
@Test 
public void whenCreateSpy_thenCreate() { 
    List spyList = Mockito.spy(new ArrayList()); 
    spyList.add("one"); 
    Mockito.verify(spyList).add("one"); 
    assertEquals(1, spyList.size()); 
} | 
| 
Unit Test Spring MVC Rest Service:
  MockMVC, JUnit, Mockito | ||||||||||||||||
| 
What
  are the dependencies  
 | ||||||||||||||||
| 
public
  class UserControllerUnitTest { 
    private MockMvc mockMvc; 
    @Mock 
 
    private UserService userService; 
    @InjectMocks 
    private UserController userController; 
    @Before 
    public void init(){ 
        MockitoAnnotations.initMocks(this); 
        mockMvc = MockMvcBuilders 
               
  .standaloneSetup(userController) 
                .addFilters(new CORSFilter()) 
                .build(); 
    } | ||||||||||||||||
| 
WHAT ARE THE CORE STEPS INVOLVED IN MOCKITO ? | |||||||||||||||||||
| 
1.Creating Mocks 
 
 
 
 
 
 
 
 
 
 | |||||||||||||||||||
| 
2. Stubbing Value 
Stubbing values can stimulate the behavior of existing
  code or be a temporary substitute for yet-to-be-developed code. By default, for all methods that
  return value, mock returns null, an empty collection or appropriate
  primitive/primitive wrapper value (e.g: 0, false, …). You can override the
  stubbing values as below. Once stubbed, the method will always return
  stubbed value regardless of how many times it is called. For a method with a
  void return, ususally we do not need to stub it. 
 
 
 
 | |||||||||||||||||||
| 
3.
  Verifying a method was called 
What is the difference between “stubbying” and
  “verifying”? In a nutshell, “stubbing” should be used for the items that you
  don’t really care about, but they are necessary to make the test pass. In
  contrast, “verifying” should be used to verify the behavior 
 
 
 
 | |||||||||||||||||||
| 
4.
  Verifying the Order of Calls to a Single Object | |||||||||||||||||||
| 
5.
  Verifying the Order of Calls Across Multiple Objects | |||||||||||||||||||
| 
6.
  Verifying That Only the Expected Calls Were Made | |||||||||||||||||||
| 
7.
  Verifying That Specific Calls Are Not Made | |||||||||||||||||||
SPRING MOCKITO
| 
Spring MVC RESTFul Web
  Service CRUD Example | 
| 
-config 
-filter 
-controller 
-model 
-service | 
| 
Creating web service in spring mvc | 
| 
http://memorynotfound.com/spring-mvc-restful-web-service-crud-example/ | 
| 
What are the maven dependencies used
  in mockito ? | 
| 
·     
  Add
  the following dependencies to your project’s pom.xml and maven will resolve
  the dependencies automatically. 
·     
  org.hamcrest:hamcrest We use hamcrest for writing assertions on the response. We can use a
  variety of Matchers to validate if the response is what we expect. 
·     
  org.springframework:spring-test contains MockMvc and other test classes which we can use
  to perform and validate requests on a specific endpoint. 
·     
  org.mockito:mockito-core mocking framework for mocking data. 
·     
  com.jayway.jsonpath:json-path-assert Using jsonPath() we can access the
  response body assertions, to inspect a specific subset of the body. We can
  use hamcrest Matchers for asserting the value found at the JSON path. | 
| 
·     
   | 
| 
STEP 1 : Initialize classes | 
| 
public class UserControllerUnitTest { 
    private
  MockMvc mockMvc; 
    @Mock 
    private
  UserService userService; 
    @InjectMocks 
    private
  UserController userController; 
    @Before 
    public
  void init(){ 
        MockitoAnnotations.initMocks(this); 
       
  mockMvc = MockMvcBuilders 
               
  .standaloneSetup(userController) 
               
  .addFilters(new
  CORSFilter()) 
               
  .build(); 
    } 
    // ... 
} | 
| 
MockMvc is the main entry point for server-side Spring MVC test support.
  Perform a request and return a type that allows chaining further actions,
  such as asserting expectations, on the result. 
@Mock creating a mock. This can also be achieved by using org.mockito.mock(..) method. 
@InjectMocks injects mock or spy fields into tested objects automatically. 
MockitoAnnotations.initMocks(this) initializes fields annotated with Mockito annotations. 
MockMvcBuilders.standaloneSetup(..).build() builds a MockMvc instance
  by registering one or more @Controller instances and configuring Spring MVC infrastructure
  programmatically. | 
| 
References | 
| 
http://memorynotfound.com/unit-test-spring-mvc-rest-service-junit-mockito/ | 
-->
JUNIT : MOCKITO
@BeforeClass : BeforeAll
@Test(expected = Arithmetic....Exception)
@Test(timeout =1000)
@After/Afterclass
@mock
@injectmocks
@runswith(Junitrunner.class)
@mock()
when ()doReturn()
verify()
verify()
ArgumentWatcher
ArgumentCaptor
doAnswer......when
when ....thenAnswer
@BeforeClass : BeforeAll
@Test(expected = Arithmetic....Exception)
@Test(timeout =1000)
@After/Afterclass
@mock
@injectmocks
@runswith(Junitrunner.class)
@mock()
when ()doReturn()
verify()
verify()
ArgumentWatcher
ArgumentCaptor
doAnswer......when
when ....thenAnswer
| JUnit 4 | Description | 
| import org.junit.* | Import statement for using the following annotations. | 
| @Test | Identifies a method as a test method. | 
| @Before | Executed before each test. It is used to prepare the test environment (e.g., read input data, initialize the class). | 
| @After | Executed after each test. It is 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 | Executed once, before the start of all tests. It is used to perform time intensive activities, for example, to connect to a database. Methods marked with this annotation need to be defined as static to work with JUnit. | 
| @AfterClass | Executed once, after all tests have been finished. It is used to perform clean-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 or @Ignore("Why disabled") | Marks that the test should be disabled. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included. It is best practice to provide the optional description, why the test is disabled. | 
| @Test (expected = Exception.class) | Fails if the method does not throw the named exception. | 
| @Test(timeout=100) | Fails if the method takes longer than 100 | 
-->
| Statement | Description | 
| fail(message) | 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 message parameter is optional. | 
| assertTrue([message,] boolean condition) | Checks that the boolean condition is true. | 
| assertFalse([message,] boolean condition) | Checks that the boolean condition is false. | 
| assertEquals([message,] expected, actual) | Tests that two values are the same. Note: for arrays the reference is checked not the content of the arrays. | 
| assertEquals([message,] expected, actual, tolerance) | Test that float or double values match. The tolerance is the number of decimals which must be the same. | 
| assertNull([message,] object) | Checks that the object is null. | 
| assertNotNull([message,] object) | Checks that the object is not null. | 
| assertSame([message,] expected, actual) | Checks that both variables refer to the same object. | 
| assertNotSame([message,] expected, actual) | Checks that both variables refer to different objects | 
-->
There are 3 ways to run tests
- Junitcore
- Run Suite.class
- Simply run class
Junitcore
Suite
3. Simply run class
| 
@Test(expected = ArithmeticException.class) :consider the methods pass if @Test | 
| 
@Test(timeout = 1000) :let the methods fail if execution takes more than1000  millisecods | 
| 
import static org.junit.Assert.assertEquals; | 
| 
assertEquals(message,messageUtil.salutationMessage()); | 
| 
assertNotEquals() | 
| 
assertTrue() | 
| 
assertNotTrue() | 
| 
assertNotNull() | 
| 
assertThat | 
Public class messageTest{  
 @BeforeClass  
  Public void beforeClass(){  
 }  
 @Before  
  Public void setup(){  
 }  
 @Test  
 public void testMessage(){  
 assertTrue(5>3);  
 }  
   @Test  
 public void testPrintMessage1() {  
         String str1= "test";  
            String str2 = "test2";  
            // assertEquals(str1,str2);  
             assertNotEquals(str1, str2);  
        }  
 @After  
 Public void setup(){  
 }  
 @AfterClass  
  Public void beforeClass(){  
 }  
 }  
 .  | MOCKITTO CHEATSHEET | 
| @RunWith(PowerMockRunner.class) – Tell Junit that run this test using PowerMockRunner | 
| @PrepareForTest(A.class) – This is needed when we need to test static methods of A class | 
| AService mock = PowerMockito.mock(A.class) – Creating a mock for A class | 
| PowerMockito.when(mock.mockedMethod()).thenReturn(value) – When mockedMethod is called in the code, then return the value specified here. | 
| PowerMockito.doNothing().when(mock).method() – do nothing when method() is called on mock object | 
| Mockito.verify(mock).someMethod() – Verify that someMethod was called on mock once. | 
| Mockito.verify(mock, times(n)).someMethod() – someMethod called n number of times | 
| Mockito.verify(mock, never()).someMethod() – someMethod called n number of times | 
| Mockito.verify(mock, atLeastOnce()).someMethod() – self explanatory | 
| Mockito.verify(mock, atLeast(n)).someMethod() – self explanatory | 
| Mockito.verify(mock, atMost(n)).someMethod() – self explanatory | 
| Static | 
| PowerMockito.mockStatic(A.class) – mock all static methods of class A | 
| PowerMockito.doNothing().when(A.class) | 
| A.staticMethod(value); – Nothing to be done when staticMethod(value) is called on class A | 
| PowerMockito.doNothing().doThrow(new IllegalStateException()).when(A.class) | 
| A.staticMethod(value); – Throw IllegalStateException when staticMethod(value) is called on class A | 
| //We first have to inform PowerMock that we will now verify | 
| //the invocation of a static method by calling verifyStatic. | 
| PowerMockito.verifyStatic(); | 
| //Then we need to inform PowerMock about the method we want to verify. | 
| //This is done by actually invoking the static | 
| A.staticMethod(); | 
| @Before – annotation for a method that does the set up before starting the test. | 
| InOrder verification | 
| //First we have to let PowerMock know that the verification order is | 
| //going to be important. This is done by calling Mockito.inOrder and passing | 
| //it the mocked object. | 
| InOrder inOrder = Mockito.inOrder(mock); | 
| //Next, we can continue our verification using the inOrder instance | 
| //using the same technique as seen earlier. | 
| inOrder.verify(mock).isNew(); | 
| inOrder.verify(mock).update(); | 
| inOrder.verify(mock, Mockito.never()).create(); | 
| Constructor | 
| PowerMockito.whenNew(A.class).withArguments(mock, “msg”).thenReturn(object) | 
| PowerMockito.verifyNew(A.class).withArguments(mock, “msg”) | 
| PowerMockito.verifyNew(A.class, times(n)).withArguments(mock, “msg”) | 
| The class creating an object of A will be needed to be in @PrepareForTest | 
| Matchers | 
| PowerMockito.when(mock.method(Mockito.startsWith(“somestring”))).thenReturn(objValue); | 
| Assert.assertSame(objValue, mock.method(“somestring123”)); | 
| Assert.assertSame(objValue, mock.method(“somestring456”)); | 
| PowerMockito.when(mock.method(Mockito.argThat(new ArgumentMatcher){public void matches(Object obj)….}).thenReturn(value); – Use the custom matcher to match the argument and return the value specified. | 
| Mockito.eq(value) | 
| Mockito.matches(regex) | 
| Mockito.anyString, anyFloat, anyDouble, anyList, and so on | 
| Mockito.isNull | 
| Mockito.isNotNull | 
| Mockito.isA | 
| Mockito.endsWith | 
| Answer Interface | 
| When thenReturn() is not practical, use Answer interface | 
| PowerMockito.when(mock.method()).then(new Answer | 
| public T answer(InvocationOnMock invocation) { | 
| …invocation.getArguments()…. | 
| } | 
| }); | 
| PowerMockito.mock(A.class, Answer obj) – This will act as default answer for all the invocation on this mock object. | 
| Spy – Partial Mocking (some methods) of classes | 
| //Following is the syntax to create a spy using the PowerMockito.spy method. | 
| //Notice that we have to pass an actual instance of the EmployeeService class. | 
| //This is necessary since a spy will only mock few methods of a class and | 
| //invoke the real methods for all methods that are not mocked. | 
| final EmployeeService spy = PowerMockito.spy(new EmployeeService()); | 
| //Notice that we have to use the PowerMockito.doNothing().when(spy).createEmployee() | 
| //syntax to create the spy. This is required because if we use the | 
| //PowerMockito.when(spy.createEmployee()) syntax will result in calling | 
| //the actual method on the spy. | 
| //Hence, remember when we are using spies, | 
| //always use the doNothing(), doReturn() or the //doThrow() syntax only. PowerMockito.doNothing().when(spy) | 
| .createEmployee(employeeMock); | 
| Mocking private methods | 
| PowerMockito.doNothing().when(spy, | 
| “createEmployee”, employeeMock); | 
| PowerMockito.verifyPrivate(spy) | 
| .invoke(“createEmployee”, employeeMock); verify simple invocation on mock List 
verify number of interactions with mock mockedList.size(); verify(mockedList, times(1)).size(); verify no interaction with the whole mock occurred List verify no interaction with a specific method occurred List verify there are no unexpected interactions – this should fail: List verify order of interactions List verify an interaction has not occurred List verify an interaction has occurred at least certain number of times List 
verify interaction with flexible/any argument List 
verify interaction using argument capture List | 



 
 
 
 
No comments:
Post a Comment