Question

I use JUnit for unit-testing. I use JMockit to mock up some java.util classes in my unit tests:

   new MockUp<PrintWriter>() { //HERE UNIT TESTS HANG ON
        @SuppressWarnings("unused")
        @Mock(invocations = 5)
        public void print(String s) {
            System.out.print(s);
        }

        @SuppressWarnings("unused")
        @Mock(invocations = 1)
        public void flush() {}
    };

Problem: My unit test just hang on at mockup definition.

Question: May you suppose the problem?

My dependencies:

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
    <dependency>
        <groupId>com.googlecode.jmockit</groupId>
        <artifactId>jmockit</artifactId>
        <version>1.7</version>
    </dependency>
</dependencies>
Was it helpful?

Solution

Please, have a look on this page:

http://jmockit.googlecode.com/svn-history/r1123/trunk/www/installation.html

at the step 4.

You are probably missing a jmockit agent as default VM argument:

-javaagent:<path_to>\jmockit.jar

OTHER TIPS

The test class below works fine for me, using JMockit 1.7.

@RunWith(JMockit.class)
public class PrintWriterTest
{
    @Test
    public void useMockedPrintWriter() throws Exception {
        new MockUp<PrintWriter>() {
            @Mock(invocations = 5) void print(String s) { System.out.print(s); }
            @Mock(invocations = 1) void flush() {}
        };

        writeTextFileWithFiveLines();
    }

    void writeTextFileWithFiveLines() throws Exception {
        PrintWriter pw = new PrintWriter("temp.txt");
        pw.print("line1");
        pw.print("line2");
        pw.print("line3");
        pw.print("line4");
        pw.print("line5");
        pw.flush();
    }

    @Test
    public void useNonMockedPrintWriter() throws Exception {
        writeTextFileWithFiveLines();
    }
}

Note 1: The use of @RunWith(JMockit.class) above is not required; its advantage is only that it avoids the need to either have jmockit.jar precede junit.jar in the classpath or to have -javaagent:jmockit.jar as a JVM initialization parameter.

Note 2: The invocations = n constrains used above are entirely optional.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top