I just started using JMockit and I am a bit confused on some basics of JMockit, in terms of when mock object is created, mocked object scope and what is the effect of mock etc. Please help with the following questions.
My questions refer to the following code:
public class MyClassTest
{
@Mocked({"method1","method2"})
ClassA classA; //ClassA has only static method
@Mocked
ClassB classB;
@Test
public void test1()
{
new NonStrictExpectations() {{
MyClassA.method3(classB);
result = xxx;
}};
// testing code
....
// verification
...
}
@Test
public void test2(@Mocked ClassC classC)
{
...
}
}
Questions:
(1) For junit, the instance variable is newly created for each test (like test1(), test2()), right? Is it true that before each test runs, a new mocked instance of ClassB is created?
(2) It mocks the class. It makes all methods in ClassB mocked for all tests (test1() and test2() in this case), right?
(3) If methods are specified for mocked object, like "@Mocked({"method1","method2"}) ClassA classA;", it means only method1 and method2 can be mocked? Can other methods be added to be mocked in Expectations for a test?
I assume this mock should not affect other tests? Is it true that ClassC is only mocked in test2()?
(1) For expectation specified in a test, is its scope local to the test, meaning the mocked method is only effective in this test? For example, ClassA.method3() is only mocked in test1(), right?
(2) The recorded method in expectation only runs when the matching method is invoked from the testing code, is it? If recorded method parameter does not match, will it run the real method?
I am getting an exception in ClassA.method3() when running test1(). Somehow the real method of ClassA.method3() is executed and gave exception. I guess it is due to parameter mismatch for ClassA.method3()?
Answering your questions:
(1) Yes; (2) yes; (3) yes, and other methods cannot be mocked in this same test class.
Yes, only in the test which has the mock parameter.
(1) Right, the expectation is only valid within the scope where it's recorded. (2) No, once mocked, the real implementation of a method is never executed.
As for the exception you get, I can't tell why it happens without seeing a complete test.