smali

smali

вторник, 24 февраля 2015 г.

JMockit Tutorial:Learn it today with examples


http://abhinandanmk.blogspot.com/2012/06/jmockit-tutoriallearn-it-today-with.html

JMockit is one of the many mocking frameworks available for unit testing in Java. If you have to unit test you'll invariably end up mocking objects for third party classes and for stubbing.

I assume you already know JUnit. We'll see step by step in very short tutorials that'll help you start using jmockit. I'll be trying to keep each one as crisp as possible. If you want more details.You can ask them in comments section below...

I am yet to understand some of the JMockit features completely, so please bear with me if I have not covered it in entirety. 


  1. What is Mocking in unit Testing?
  2. How does JMockit support mocking?
  3. How to add JMockit to an eclipse project?
  4. How to run a test case with JMockit?
  5. How to mock default constructors(or constructors with no parameters) in JMockit?
  6. How to mock constructors with parameters (or those that take arguments) ?
  7. How to mock static initialization blocks in JMockit?
  8. How to mock public methods in JMockit
  9. How to mock  private methods in JMockit?
  10. How to mock static methods in JMockit?
  11. How to invoke or test private methods in JMockit?
  12. How to throw exceptions in an Expectations block?
  13. Some more JMockit utilities before signing off.


How to mock constructors in JMockit?

Consider the code below:



?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/************************* Person.java ****************/
public class Person {
 private String name;
   
  
 public Person(){
  name = "Default Abhi";
 }
  
 public String getName() {
  return name;
 }
  
 public void setName(String name) {
  this.name = name;
 }
}
/******************* PersonTestConstructor.java ***********/
public class PersonTestConstructor {
 @Test
 public void testGetName() {
  new MockUp<Person>() {
   @Mock
   public void $init() {
    //Dont assign name variable at all
    //Leave it null
   }
  };
   
  Person p = new Person();
  String name = p.getName();
   
  assertNull("Name of person is null",name);
 }
}
Here we have a class Person whose default constructor initializes the name variable to "Default Abhi" In the test class PersonTestConstructor, I mock the constructor by using a special mock method $init to do nothing.

Remember the to put the @Mock  annotation above. I have spent hours trying to debug only to find out that I forgot.