Loading
 
What's Next: View All Tutorial →

How to mock constructor with and without Parameter in JMockit using inline Mockup

In this article you will learn, How to mock constructor with and without Parameter in JMockit using inline Mockup   User Java class This class has two construct with and without param   package com.mycompany.app; public class User...

Published Date: 29/04/2015  Last Modified Date: 29/04/2015    New Post



In this article you will learn, How to mock constructor with and without Parameter in JMockit using inline Mockup
 

User Java class

This class has two construct with and without param
 
package com.mycompany.app;

public class User {

    private String name;

    public User() {
        this.name = "Catchmycity.com";
    }

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


Test Class

package com.mycompany.app;

import mockit.Mock;
import mockit.MockUp;
import mockit.integration.junit4.JMockit;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(JMockit.class)
public class UserTest {

    @Test
    public void testUser() {

        //To mock the default constructor
        new MockUp<User>() {
            @Mock
            public void $init() {
            }
        };

        User user = new User();
        //User.getName returning null as we mocked instead of Catchmycity.com
        Assert.assertEquals(user.getName(), null);

    }

    @Test
    public void testParameterizedConstructor() {

        //To mock the default constructor
        new MockUp<User>() {
            @Mock
            public void $init(String name) {

            }
        };

        User user = new User("John");
        System.out.println(user.getName());  //return null instead of John as we mocked
        Assert.assertEquals(user.getName(), null);

    }

}


new MockUp<User>()   - To define a Mockup Class, After define, we call mock all the constructor , static and mothod inside the class can be mocked

@Mock  - Declare at the top of the method to say, the method is mocked

$init  - To map the constructor in Jmockit

public void $init() {   - Default Constructor

public void $init(String name) {  - Parameterised constructor

 
Awaiting for Administrator approval





Tags: JMockit JUnit

← Back to list


Related Post




×