Advanced Java library for integration testing, mocking, faking, and code coverage

Overview

Codebase for JMockit 1.x releases - Documentation - Release notes

How to build the project:

  • use JDK 1.8 or newer
  • use Maven 3.6.0 or newer; the following are the top-level modules:
    1. main/pom.xml: builds jmockit-1.n.jar, running JUnit 4 and TestNG test suites
    2. coverageTests/pom.xml: runs JUnit 4 tests for the coverage tool
    3. samples/pom.xml: various sample test suites (tutorial, LoginService, java8testing) using JUnit 4, 5, or TestNG 6
    4. samples/petclinic/pom.xml: integration testing example using Java EE 8
Comments
  • Restore ability to mock internal classes

    Restore ability to mock internal classes

    As of JMockit 1.27 mocking of classes from the same codebase produces an error saying it is not allowed and mocking private methods produces an error. I see you closed issue 324 so this is an enhancement.

    Can you remove that check or put in a way to disable it - maybe with SuppressWarnings? I find it useful to mock out methods that setup FileWriters and replace them with mock methods that setup StringWriters so no files are written during test runs. I could probably use Deencapsulation to modify it or make the method protected and then use a subclass, but I don't always have direct access to the class - e.g. I am testing some class that uses a helper object that has a FileWriter.

    Thanks.

    other 
    opened by pamcevoy 20
  • Some tested classes are not included in coverage report

    Some tested classes are not included in coverage report

    Please provide the following information:

    • Version of JMockit that was used: 1.24
    • Description of the problem or enhancement request: Using jmockit for mocking with JUnit 4 as test runner. Also using jmockit for code coverage. The issue I am having is that when running coverage some classes are not being outputted to the html coverage report. Other source files in this directory are being outputted to the html. The test suite is testing the classes that are not being outputted.

    I do not have any jmockit 'excludes' system JVM arguments set.

    Are there any reasons that some classes in a package would be included and some classes would not?

    question 
    opened by eoghanoh1 19
  • Verify that already loaded JMockit version is the expected version

    Verify that already loaded JMockit version is the expected version

    This PR verifies that if a JMockit agent is already loaded in the current JVM, that it is the version expected. This prevents e. g. if you start a JVM with -javaagent:jmockit-1.8.jar but have jmockit-1.24.jar in your classpath to run your tests with that incompatibilites arise.

    This also covers the case that you load JMockit in an application server to run integration tests from a branch using JMockit 1.8 and then run on the same application server instance integration tests from a branch using JMockit 1.24 without restarting the application server.

    opened by Vampire 18
  • JMockit on multiple class loaders does not work nicely

    JMockit on multiple class loaders does not work nicely

    I'm not 100% sure how it is intended with the mocking bridge fields that are stored in NegativeArraySizeException or similar, but it doesn't work too nicely if you use JMockit from multiple classloaders.

    To reproduce the error, just comment out the MockingBridge.setMockingBridgeFields(); line from my PR #309. Tests that use mocking bridge fields will fail thereafter, e. g. changeContextCLDuringReplay() will fail with a NullPointerException.

    The problem here is, if you initialize JMockit on some class loader B where it was not initialized yet, the mocking bridge fields in NegativeArraySizeException or similar are updated to the ones from that class loader B and the ones from class loaders (A) where JMockit was initialized before are lost at this place.

    If you then use JMockit on the class loader A where it was initilized before B, the classes from A are used. But the transformed-in calls that use the mocking bridge fields in NegativeArraySizeException or similar use the mocking bridges from class loader B which does not harmonize of course, as then various static fields etc. are not like expected, like e. g. mockit.internal.state.MockClasses#mockupClassesToMockupInstances which misses the instances in the B version that are present in the A version.

    I'd like to report this either as bug if JMockit should work fine with multiple classloaders, or as improvement request if this is expected behaviour.

    Also if this is expected behaviour for now, please at least document it somewhere (I didn't find it mentioned) and maybe add some check that recognizes that the mocking bridge fields class loader does not match the other JMockit classes class loader and raise some meaningful error that explains that you can only use JMockit on one class loader at a time and if you switched to a new class loader that you cannot easily go back to the old one.

    enhancement 
    opened by Vampire 16
  • Optional expectations no longer possible after removal of NonStrictExpectations

    Optional expectations no longer possible after removal of NonStrictExpectations

    Suppose I have a mock with a(), b() and c() methods each returning some value. My class under test can potentially call any of those. Or any combination of those. Or none. The nature of calls and order of those is really down to implementation details and I don't want to replicate its logic in my test (and I really shouldn't). All I know is that invocations of a(), b() and c() or any combination of those are valid interactions and should return some values.

    Used to be easily done with NonStrictExpectations, but now that is's gone there is no way to model this behavior. Expectations simply ignores minTimes as per stacktrace, while StrictExpectations enforces the order on invocations. So am I missing something or there is indeed no way of setting up such a scenario?

    It has to be stated that a MockUp could be used, of course, with defined a(), b() and c(). But then I won't be able to specify other expectations on my mock using the Expectations syntax nor verify interactions using Verifications(), which is extremely useful.

    Is there a solution? Especially unfortunate is that both jMock (via allowing) and Mockito (via VerificationMode) support this functionality.

    question 
    opened by wigbam 15
  • Conflict between jmockit and jacoco

    Conflict between jmockit and jacoco

    Related to this issue https://github.com/jacoco/jacoco/issues/272

    The problem is still happening in the latest versions of jacoco/jmockit

    This project reproduces the issue: https://github.com/henri-tremblay/jacocomockit

    When the line in the readme is executed, you will get this exception: java.lang.UnsupportedOperationException: class redefinition failed: attempted to change the schema (add/remove fields)

    jmockit 1.14 and jacoco 0.7.2.201409121644 is used

    other 
    opened by henri-tremblay 15
  • Injection fails with two constructors present (one @Autowired)

    Injection fails with two constructors present (one @Autowired)

    I'm not sure if this is a bug, or by design. I have 2 constructors defined for a class (one autowired and one not).

    public class Counter {
        private Data data = new Data();
    
        @Autowired
        public Counter(Data data){
            this.data = data;
        }
    
        public Counter(){}
    
        public void printData(){
            System.out.println(data.toString());
        }
    }
    

    However, unless I defined a @Injectable in my test class, I get the following error:

    java.lang.IllegalArgumentException: No constructor in tested class that can be satisfied by available injectables
      public test.Counter(test.Data)
        disregarded because no injectable was found for parameter "data"
    

    Should JMockit not detect the ability to construct the class using the second empty constructor? I'm using JMockit 1.19.

    I would have expected the following test class to work:

    @RunWith(JMockit.class)
    public class CounterTest {
        @Tested(fullyInitialized=true) Counter counter;
    
        @Test
        public void testPrint(){
            counter.printData();
        }
    }
    

    Thanks,

    Eric

    question 
    opened by benze 14
  • Please clarify the -javaagent requirements for gradle

    Please clarify the -javaagent requirements for gradle

    In the release notes for 1.42, you say that the -javaagent is now required, but only the Maven example shows it being configured. If it is not required for Gradle, can you clarify that in the documentation, or update the example gradle configuration with one that sets the -javaagent

    documentation 
    opened by charlesritchea 13
  • The temporary directory is filled with jmockit....jar files

    The temporary directory is filled with jmockit....jar files

    If you use JMockit with WildFly using Attach API and the temp jmockit....jar file creation, the temp files are not cleaned, but each time you restart WildFly and thus JMockit gets loaded via Attach API afresh, a new jmockit....jar file is generated in the temporary folder and is never cleaned up. Those files are only 4 KiB in size, but over time they will still fill up the temporary directory unnecessarily.

    I'd like to suggest adapting a part of my former pull-request, where the MD5 of the generated file is calculated and then the file is renamed to jmockit-<MD5>.jar if that file is not present already or has the wrong MD5 sum, and if it is present already with the correct MD5 sum, the new temp file should simply be deleted. Then as agent, the jmockit-<MD5>.jar file is used. This way only a new persistent temporary file is generated if the content, i. e. the InstrumentationHolder class got changed.

    enhancement 
    opened by Vampire 13
  • MissingInvocation when minTimes = 0

    MissingInvocation when minTimes = 0

    JMockit Version 1.26 with the latest version of JMockit, minTimes does not seem to work the same as before. When a method call in an Expectations block has the minTimes set to 0, a test which does not call that method will fail with a MissingInvocation of that method call.

    Here is an example test case that fails in 1.26, but passes in 1.25.

    import mockit.Expectations;
    import mockit.Injectable;
    import mockit.Tested;
    import mockit.integration.junit4.JMockit;
    import org.junit.Assert;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    
    import java.util.Arrays;
    import java.util.List;
    
    @RunWith(JMockit.class)
    public class MinTimesTest {
    
        public static class UnitUnderTest {
            public String doSomething(List<DependencyAbc> dependencies) {
                StringBuilder something = new StringBuilder();
                for (DependencyAbc dependency : dependencies) {
                    if (dependency.getValue() > 0) {
                        something.append(dependency.getName());
                    }
                }
                return something.toString();
            }
        }
    
        public static class DependencyAbc {
            public int getValue() {
                return 0;
            }
            public String getName() {
                return null;
            }
        }
    
        @Tested
        UnitUnderTest unit;
    
        @Injectable
        DependencyAbc dependency1;
    
        @Injectable
        DependencyAbc dependency2;
    
        final class DependencyExpectations extends Expectations {
            public DependencyExpectations(DependencyAbc dependency, int value, String name) {
                dependency.getValue(); result = value; minTimes = 0;
                dependency.getName(); result = name; minTimes = 0;
            }
        }
    
        @Test
        public void testMinTimes() {
    
            new DependencyExpectations(dependency1, -1, "dependency1");
            new DependencyExpectations(dependency2, 1, "dependency2");
    
            String result = unit.doSomething(Arrays.asList(dependency1, dependency2));
            Assert.assertEquals("dependency2", result);
        }
    }
    

    MinTimesTest.txt

    This used to be taken care of by NonStrictExpectations. Then that class was removed and I think it was intended to be replaced with a regular Expectations block with minTimes = 0 for each method. If this is not the case then what is the recommended way to have "optional" method expectations?

    question 
    opened by mdamone 13
  • Invalid conditional statement inside expectation block

    Invalid conditional statement inside expectation block

    Hi,

    I'm getting IllegalArgumentException "Invalid conditional statement inside expectation block" when having an if statement inside my expectation block. It was working in v1.9 and when upgrading to 1.14, it throws me this Exception.

    private void setUpExpectations(final SetUpNewServerFixture fixture, final boolean domainNameExists) {
            new NonStrictExpectations() {{
                trialServerRepository.domainNameExists(fixture.domainName);
                result = domainNameExists;
    
                if (!domainNameExists) {
                    final TrialServer trialServer = createDefaultTrialServer(fixture.companyDomain,
                                                                             fixture.numOfTrialServersInDomain);
                    trialServerRepository.save(withAny(trialServer));
                    result = trialServer;
                }
            }};
        }
    
    question 
    opened by henryken 13
  • Add support for Java 11+

    Add support for Java 11+

    NOTE: The work on this PR and a few others is mirrored on https://github.com/hazendaz/jmockit1/ since it seems like the maintainers of this project are MIA


    Encountered some compatibility issues with a project due to outdated bytecode handling. This PR addresses the cases I've encountered personally but should also address the following issues:

    • https://github.com/jacoco/jacoco/issues/896 (Some of the changes are based on the artifact com.github.hazendaz.jmockit:jmockit:1.49.2 which is mentioned in the thread though I could not find @hazendaz hosting the source currently)
    • #729

    Other changes under the hood:

    • Change bytecode handling to explicitly fail rather than assume a type in switch cases (Assisted in debugging, and failing makes the cause more clear than undefined behavior caused by ignoring the issue with fallback behavior)
    • Use full names instead of shorthand for constants (minor legibility improvement)
    • Use objenesis instead of direct sun reflection-factory for instance creation
    • Remove junit platform exclusion in pom.xml, resolving some failures with IntelliJ integration

    Testing

    You can test the validity of the changes within this project by forcing maven to execute the project in a Java 11+ context. I suggest the maven toolchain plugin for this:

    Index: main/pom.xml
    <+>UTF-8
    ===================================================================
    diff --git a/main/pom.xml b/main/pom.xml
    --- a/main/pom.xml	(revision 5c6a2dfc6042ebf8d99770a7e9167bf3c26149e8)
    +++ b/main/pom.xml	(date 1665027301503)
    @@ -66,10 +66,29 @@
           </resources>
           <plugins>
              <plugin>
    +            <groupId>org.apache.maven.plugins</groupId>
    +            <artifactId>maven-toolchains-plugin</artifactId>
    +            <version>3.1.0</version>
    +            <configuration>
    +               <toolchains>
    +                  <jdk>
    +                     <version>11</version>
    +                  </jdk>
    +               </toolchains>
    +            </configuration>
    +            <executions>
    +               <execution>
    +                  <goals>
    +                     <goal>toolchain</goal>
    +                  </goals>
    +               </execution>
    +            </executions>
    +         </plugin>
    +         <plugin>
                 <artifactId>maven-compiler-plugin</artifactId><version>3.8.0</version>
                 <configuration>
                    <encoding>UTF-8</encoding>
    -               <source>1.7</source><target>1.7</target>
    +               <release>11</release>
                    <compilerArgs><arg>-Xlint:none</arg></compilerArgs>
                    <useIncrementalCompilation>false</useIncrementalCompilation>
                 </configuration>
    

    I tested up to Java 17 with all tests passing.

    opened by Col-E 1
  • Horrible implementation of stack variation and more

    Horrible implementation of stack variation and more

    https://github.com/jmockit/jmockit1/blob/5c6a2dfc6042ebf8d99770a7e9167bf3c26149e8/main/src/mockit/asm/jvmConstants/JVMInstruction.java#L15-L19

    This might save some space when writing, but the readability is horrible. "How much stack does this specific instruction modify?"

    A better way to do it would be to make an enum with all relevant instructions, store them by index, and put the info in their params.

    opened by 0x3C50 1
  • Mocks created by JUnit4 tests are not cleaned up when run with JUnit5

    Mocks created by JUnit4 tests are not cleaned up when run with JUnit5

    Please provide the following information:

    • Version of JMockit that was used: 1.49.a (see https://github.com/JOSM/jmockit1/tree/josm-fixes )

    • Description of the problem or enhancement request: When running JUnit4 and JUnit5 tests together, JMockit does not properly cleanup after mocks are created in the JUnit4 tests.

    Problem code: https://github.com/jmockit/jmockit1/blob/master/main/src/mockit/internal/startup/JMockitInitialization.java#L34

    Workaround for non-patched releases: Create a new mockit.internal.state.SavePoint before each test (i.e., in a @Before method) and then call the rollback method in an @After method. See https://josm.openstreetmap.de/changeset/18551/josm/ for an example using a custom TestRule.

    • Check the following:
    • [x] If a defect or unexpected result, JMockit project members should be able to reproduce it. For that, include an example test (perhaps accompanied by a Maven/Gradle build script) which can be executed without changes and reproduces the failure.

    • [ ] If an enhancement or new feature request, it should be justified by an example test demonstrating the validity and usefulness of the desired enhancement or new feature.

    • [x] The issue does not fall outside the scope of the project (for example, attempting to use JMockit APIs from Groovy or Scala code, or with an Android runtime).

    • [x] The JDK where the problem occurs is a final release, not a development build.

    opened by tsmock 0
  • MissingInvocation occurs when with(new Delegate,..) api is used in Verifications.

    MissingInvocation occurs when with(new Delegate,..) api is used in Verifications.

    Hello, The version is jmockit 1.9. When I upgrade the version to 1.36, the problem disappears,. But, I find out some usages of lower version are removed in higher version,so maybe the project will be in trouble. And the problem code as the following,

    `public class XXXTest { @Mocked Compute compute;

    @Test public void test_X() { new Expectations(){ { compute.testRef((MockClazzOne) any); result=1; } }; new HelloWorldMock().insertOneData(1);

    new Verifications() { { compute.testRef(with(new Delegate(){ @Override public boolean equals(Object o) { MockClazzOne clazzOne = (MockClazzOne)o; return clazzOne.getF1() == 1; } })); times=1; } } } }

    public class HelloWorldMock { public int insertOneData(int f1) { Compute compute = new Compute(); MockClassOne one = new MockClassOne(); one.setF1(f1); return compute.testRef(one); } } `

    opened by UchihaYong 0
  • MissingInvocation occurs when with(new Delegate,..) api is used in Verifications.

    MissingInvocation occurs when with(new Delegate,..) api is used in Verifications.

    Hello, The version is jmockit 1.9. When I upgrade the version to 1.36, the problem disappears,. But, I find out some usages of lower version are removed in higher version,so maybe the project will be in trouble. And the problem code as the following,

    `public class XXXTest { @Mocked Compute compute;

    @Test public void test_X() { new Expectations(){ { compute.testRef((MockClazzOne) any); result=1; } }; new HelloWorldMock().insertOneData(1);

    new Verifications() { { compute.testRef(with(new Delegate(){ @Override public boolean equals(Object o) { MockClazzOne clazzOne = (MockClazzOne)o; return clazzOne.getF1() == 1; } })); times=1; } } } }

    public class HelloWorldMock { public int insertOneData(int f1) { Compute compute = new Compute(); MockClassOne one = new MockClassOne(); one.setF1(f1); return compute.testRef(one); } } `

    opened by UchihaYong 0
Owner
The JMockit Testing Toolkit
A Java toolkit for automated developer testing
The JMockit Testing Toolkit
Most popular Mocking framework for unit tests written in Java

Most popular mocking framework for Java Current version is 3.x Still on Mockito 1.x? See what's new in Mockito 2! Mockito 3 does not introduce any bre

mockito 13.6k Jan 9, 2023
A tool for mocking HTTP services

WireMock - a web service test double for all occasions Key Features HTTP response stubbing, matchable on URL, header and body content patterns Request

Tom Akehurst 5.3k Dec 31, 2022
WireMock - A tool for mocking HTTP services

WireMock only uses log4j in its test dependencies. Neither the thin nor standalone JAR depends on or embeds log4j, so you can continue to use WireMock 2.32.0 without any risk of exposue to the recently discovered vulnerability.

null 5.3k Dec 31, 2022
Java testing framework for testing pojo methods

Java testing framework for testing pojo methods. It tests equals, hashCode, toString, getters, setters, constructors and whatever you report in issues ;)

Piotr Joński 48 Aug 23, 2022
Isolated MinIO container management for Java code testing

TestContainers for MinIO MinIO support for the test containers project. Installation Unfortunately, TestContainers for MinIO is not available in any p

Olsi Qose 3 Sep 30, 2022
JVM version of Pact. Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project.

pact-jvm JVM implementation of the consumer driven contract library pact. From the Ruby Pact website: Define a pact between service consumers and prov

Pact Foundation 962 Dec 31, 2022
Calcite Clojure wrapper / integration

calcite-clj - Use Apache Calcite from Clojure Small library to facilitate the implementation of calcite adapters in clojure. It implements org.apache.

Eugen Stan 24 Nov 5, 2022
A modern testing and behavioural specification framework for Java 8

Introduction If you're a Java developer and you've seen the fluent, modern specification frameworks available in other programming languages such as s

Richard Warburton 250 Sep 12, 2022
ScalaTest is a free, open-source testing toolkit for Scala and Java programmers

ScalaTest is a free, open-source testing toolkit for Scala and Java programmers.

ScalaTest 1.1k Dec 26, 2022
Toolkit for testing multi-threaded and asynchronous applications

ConcurrentUnit A simple, zero-dependency toolkit for testing multi-threaded code. Supports Java 1.6+. Introduction ConcurrentUnit was created to help

Jonathan Halterman 406 Dec 30, 2022
The Enterprise-ready testing and specification framework.

Spock Framework Spock is a BDD-style developer testing and specification framework for Java and Groovy applications. To learn more about Spock, visit

Spock Framework 3.3k Jan 5, 2023
Layout and functional testing framework for websites

Galen Framework master: Galen is an open-source tool for testing layout and responsive design of web applications. It is also a powerfull functional t

Galen Framework 1.4k Dec 10, 2022
Java DSL for easy testing of REST services

Testing and validation of REST services in Java is harder than in dynamic languages such as Ruby and Groovy. REST Assured brings the simplicity of usi

REST Assured 6.2k Dec 31, 2022
A programmer-oriented testing framework for Java.

JUnit 4 JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. For more infor

JUnit 8.4k Jan 4, 2023
Java DSL for easy testing of REST services

Testing and validation of REST services in Java is harder than in dynamic languages such as Ruby and Groovy. REST Assured brings the simplicity of usi

REST Assured 6.2k Dec 25, 2022
Cucumber DSL for testing RESTful Web Services

cukes-rest takes simplicity of Cucumber and provides bindings for HTTP specification. As a sugar on top, cukes-rest adds steps for storing and using r

C.T.Co 100 Oct 18, 2022
Randomized Testing (Core JUnit Runner, ANT, Maven)

RANDOMIZED TESTING ================== JUnit test runner and plugins for running JUnit tests with pseudo-randomness. See the following for more infor

null 167 Dec 26, 2022