Loading
 
What's Next: View All Tutorial →

How to mock static method using Jmockit with MockUp and NonStrictExceptation

In this article, you will learn how to mock static method using Jmockit with MockUp and NonStrictExceptation User Class:   package com.mycompany.app; import java.util.ArrayList; import java.util.List; public class User { pub...

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



In this article, you will learn how to mock static method using Jmockit with MockUp and NonStrictExceptation

User Class:

 
package com.mycompany.app;

import java.util.ArrayList;
import java.util.List;

public class User {

    public List getSkill(String type) {

        if ("Both".equals(type)) {

            List lst = Skill.getBackendSkill();
            lst.add(Skill.getUISkills());
            return lst;
        }
        return null;
    }

}

class Skill {

    public static List getUISkills() {

        List lst = new ArrayList();

        lst.add("Extjs");
        lst.add("Jasmine");
        return lst;
    }

    public static List getBackendSkill() {
        List lst = new ArrayList();
        lst.add("Java");
        lst.add("JMockit");

        return lst;
    }
}

Test Class:
 
package com.mycompany.app;

import java.util.ArrayList;
import java.util.List;
import mockit.Expectations;
import mockit.Mock;
import mockit.MockUp;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import mockit.Verifications;
import mockit.VerificationsInOrder;
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 testMethodinClassUsingMockup() {

        new MockUp<Skill>() {
            @Mock
            public List getBackendSkill() {

                return new ArrayList();
            }

            @Mock
            public List getUISkills() {

                return new ArrayList();
            }
        };
        User user = new User();
        Assert.assertEquals(user.getSkill("Both").toString(), "[[]]"); //return [[]] instead of Java, JMockit, Extjs and jasmine as we mocked

    }

    @Test
    public void testMethodinClassUsingExpectation(@Mocked final Skill sk) {

        new NonStrictExpectations() {
            {

                sk.getBackendSkill();
                result = new ArrayList();

                sk.getUISkills();
                result = new ArrayList();
            }
        };

        User user = new User();
        Assert.assertEquals(user.getSkill("Both").toString(), "[[]]");// return  instead of Java, JMockit, Extjs and jasmine as we mocked

    }
}


Static method are more similar way as mocking public method, Please refere previous article for more details


 
Awaiting for Administrator approval





Tags: JMockit JUnit

← Back to list


Related Post




×