JUnit test fails with JMockit java.lang.IllegalStateException: Invalid context for writing expectations

@Test
public void testGetOnlyNewPartitions() throws Exception {
    setUp();
    new Expectations(){
        HiveUtil hiveUtil;
        {
            HiveUtil.getInstance(); returns(hiveUtil);
            hiveUtil.getAllpartitions(oldTable); returns(oldPartitions);
            hiveUtil.getAllpartitions(newTable); returns(newPartitions);
        }
    };
    PartitionFilter partitionFilter = new PartitionFilter(oldTable, newTable, HiveUtil.getInstance());
}

      

I am testing a module of the PartitionFilter class that uses the HiveUtil singleton class.

In my test case, the error was "java.lang.IllegalStateException: Invalid context for writing expectations" while running. Any explanation as to why this is happening?

This is the important part of my pom.xml:

<dependency>
         <groupId>org.jmockit</groupId>
         <artifactId>jmockit</artifactId>
         <version>1.13</version>
</dependency>

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
</dependency>

      

I tried to install the jmockit dependency before the junit dependency in the pom. It didn't work.

Some more research showed that I did not use the @RunWith (JMockit.class) annotation at the beginning of the class. However, when I tried to use it, I was presented with the error "Class cannot be resolved to type". I've done all the relevant imports.

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.*;

import mockit.*;
import mockit.integration.junit4.*;
import junit.framework.TestCase;

      

What am I doing wrong?

+3


source to share


1 answer


In recent versions of JMockit (since version 1.7), the use of mocking annotation is required to inject a shouted type / instance. Also, local layout fields are no longer supported. So the test should be written like this:



@Test
public void getOnlyNewPartitions(@Mocked final HiveUtil hiveUtil) throws Exception {
    setUp();

    new Expectations() {{
        hiveUtil.getAllpartitions(oldTable); result = oldPartitions;
        hiveUtil.getAllpartitions(newTable); result = newPartitions;
    }};

    PartitionFilter partitionFilter = 
        new PartitionFilter(oldTable, newTable, HiveUtil.getInstance());
}

      

+1


source







All Articles