Version of JMockit that was used: 1.21
I have interface like this.
TestInterface:
public interface TestInterface {
boolean callMethod();
}
A TestClass have field is a instance of that interface
TestClass:
public class TestClass {
private final TestInterface inner = new TestInterface() {
#Override
public boolean callMethod() {
subMethod();
return false;
}
};
public void subMethod() { System.out.println("Sub method");
};
}
I try to verify calling method by fake an interfacein this tutorial.
http://jmockit.org/tutorial/Faking.html#interfacesd
Test method.
public class TestInterfaceTest {
TestClass sut;
#Before
public void setUp() {
sut = Deencapsulation.newInstance(TestClass.class);
}
#Test
public void mockAllClassesImplementingAnInterface() {
TestInterface testInterface = new MockUp<TestInterface>() {
#Mock
public boolean callMethod(Invocation inv) {
inv.proceed(); // throw exception here -> Will my expected method be called here?
return true;
}
}.getMockInstance();
Deencapsulation.setField(sut, "INTER", testInterface);
new NonStrictExpectations() {
{
Deencapsulation.invoke(sut, "subMethod");
}
};
Boolean result = Deencapsulation.invoke(Deencapsulation.getField(sut, "INTER"), "callMethod");
assertTrue(result);
new Verifications() {
{
Deencapsulation.invoke(sut, "subMethod"); times = 1;
}
};
}
}
java.lang.IllegalArgumentException: No class with name
"ndroid.examples.helloandroid.$Impl_TestInterface" found
If you guys don't mind, could you please tell me how to resolve this byg. Many thanks.
Your problem, in my reevaluation of this issue, would seem to lie in the line inv.proceed(). You can't have that line in a Mockup of an interface.
Invocation.proceed() is intended when you want the MockUp implementation to proceed into the real code. But because you are mocking up an interface, there is no real code. You may think there is because your implementation of TestClass has an anonymous implementation of the interface, but the MockUp knows nothing of that anonymous class; it's doing a mockup of the interface and not of your anonymous implementation.
If you get rid of that line, the call to Invocation.proceed(), I think you'll find your error goes away.
Based on the guidance of #dcsohl. The code below works for me.
#Test
public void mockAllClassesImplementingAnInterface() {
// Partial mocking
new NonStrictExpectations(sut) {
{
sut.subMethod();
}
};
// Actual invocation
Deencapsulation.invoke(Deencapsulation.getField(sut, "inner"), "callMethod");
// Verify
new Verifications() {
{
Deencapsulation.invoke(sut, "subMethod");
times = 1;
}
};
}
Related
I have a class with two methods. I want to replace invocation of second method with expected result.
Here is my class under test
public class A {
public int methodOne() {
return methodTwo(1);
}
public int methodTwo(int param) {
// corresponding logic replaced for demo
throw new RuntimeException("Wrong invocation!");
}
}
And test
public class ATest {
#Test
public void test() {
final A a = spy(new A());
when(a.methodTwo(anyInt())).thenReturn(10);
a.methodOne();
verify(a, times(1)).methodTwo(anyInt());
}
}
Why I'm get an exception when start the test?
Two things that will help you here. First, from the documentation it seems you need to use the do*() api with spy() objects. Second, to call the "real" method you need to declare it specifically using doCallRealMethod()
Here's the updated test that should work for you:
public class ATest {
#Test
public void test() {
final A a = spy(new A());
doReturn(10).when(a).methodTwo(anyInt());
doCallRealMethod().when(a).methodOne();
a.methodOne();
verify(a, times(1)).methodTwo(anyInt());
}
}
I want to test this class which calls a method of interface using anonymous class.
public class ClassToTest
{
public void methodToTest()
{
InterefaceToMock interefaceToMockReference = new InterefaceToMock() {
#Override
public int methodToMock()
{
return 0;
}
};
interefaceToMockReference.methodToMock();
}
}
This is the interface
public interface InterefaceToMock
{
public int methodToMock();
}
I am using this approch to check it methodToMock is called or not
import static org.junit.Assert.*;
import org.junit.Test;
import mockit.FullVerificationsInOrder;
import mockit.Mocked;
import mockit.NonStrictExpectations;
public class TestAClass
{
#Mocked InterefaceToMock interefaceToMockReferenceMocked;
#Test
public void test1()
{
new NonStrictExpectations()
{
{
interefaceToMockReferenceMocked.methodToMock();times=1;
}
};
(new ClassToTest()).methodToTest();
new FullVerificationsInOrder(interefaceToMockReferenceMocked)
{
};
assertTrue(true);
}
}
But test case fails.
Can anyone help.
Your original test was almost correct. It declared the mock field as simply being #Mocked, which merely gives you a single mocked instance implementing the interface, and this is not the one used by the code under test. The JMockit API has another mocking annotation, however, which extends mocking to all implementation classes from a given base type, and by default affects all instances of said classes. So, the test should be changed as follows:
public class TestAClass
{
#Capturing InterfaceToMock anyImplementingInstance;
#Test
public void test1()
{
new ClassToTest().methodToTest();
new Verifications() {{
anyImplementingInstance.methodToMock();
}};
}
}
In the general case, if you have an class and you want to check whether a method on a Mock of that class is called, you use Mockito.verify.
For example:
public class AppTest {
#Test
public void testMe() {
final ITest iTest = Mockito.mock(ITest.class);
final CUT cut = new CUT(iTest);
cut.doStuff();
Mockito.verify(iTest).someStuff();
}
interface ITest {
void someStuff();
}
class CUT {
private final ITest iTest;
CUT(ITest iTest) {
this.iTest = iTest;
}
public void doStuff() {
iTest.someStuff();
}
}
}
Here, the test is whether ITest.someStuff() is called from CUT.doStuff().
Your example is undecipherable...
I'm looking for a way in JMockit to inject the private fields inside a class while maintaining the ability to trigger the real methods. I use #Injectable and #Tested offered by JMockit. But somehow after that the injected instance is not able to call the real method.
Example test:
public class TestClass {
public static class DoSomething {
private Call callee;
public void execute() {
callee.call();
}
}
public static class Call {
public void call() {
System.out.println("real");
}
}
#Tested DoSomething doSomething;
#Injectable Call call;
// nothing happens
#Test
public void testRealCall() {
doSomething.execute();
}
// invocation doesn't help either
#Test
public void testRealCallSecondTry() {
new MockUp<Call>() {
#Mock
#SuppressWarnings("unused")
public void call(Invocation inv) {
inv.proceed();
}
};
doSomething.execute();
}
// this works, but requires redundant methods
#Test
public void testRealCallThirdTry() {
new MockUp<Call>() {
#Mock
#SuppressWarnings("unused")
public void call() {
System.out.println("real");
}
};
doSomething.execute();
}
#Test
public void testFakeCall() {
new MockUp<Call>() {
#Mock
#SuppressWarnings("unused")
public void call() {
System.out.println("fake");
}
};
doSomething.execute();
}
}
Here DoSomething wraps the Call instance, which provides a way to print a message. The ideal output of the four test cases would be:
real
real
real
fake
However the actual scenario is that only 3 and 4 worked, printing:
real
fake
This shows if an instance is created using #Injectable. It's not able to directly call the original method without copying and pasting the old method body to the mocked version. That seems really awkward. Is there a workaround of this?
My understanding is that if you use #Injectable you just get an empty mock and then you can no longer call the original method.
The workaround that I would use is to do the injection "manually" like this:
public class TestClass {
public static class DoSomething {
private Call callee;
public void execute() {
callee.call();
}
}
public static class Call {
public void call() {
System.out.println("real");
}
}
#Tested DoSomething doSomething;
//#Injectable Call call;
// nothing happens
#Test
public void testRealCall() {
Deencapsulation.setField(doSomething, "callee", new Call());
doSomething.execute();
}
// invocation doesn't help either
#Test
public void testRealCallSecondTry() {
new MockUp<Call>() {
#Mock
#SuppressWarnings("unused")
public void call(Invocation inv) {
inv.proceed();
}
};
Deencapsulation.setField(doSomething, "callee", new Call());
doSomething.execute();
}
// this works, but requires redundant methods
#Test
public void testRealCallThirdTry() {
new MockUp<Call>() {
#Mock
#SuppressWarnings("unused")
public void call() {
System.out.println("real");
}
};
Deencapsulation.setField(doSomething, "callee", new Call());
doSomething.execute();
}
#Test
public void testFakeCall() {
new MockUp<Call>() {
#Mock
#SuppressWarnings("unused")
public void call() {
System.out.println("fake");
}
};
Deencapsulation.setField(doSomething, "callee", new Call());
doSomething.execute();
}
}
I ran into this question when I had the same problem. However, the existing answer don't work with newer versions of JMockit.
If a field in the tested class is annotated with #Inject, a corresponding #Injectable is required in the test class. Usually. This means that removing the #Injectable and instead mock the class with MockUp suggested in the other answer doesn't work. JMockit will complain with "Missing #Injectable for field ...".
What needs to be done instead is to change the #Injectable annotation to a #Tested annotation, i.e. change this
#Injectable Call call;
to
#Tested Call call;
call becomes a real instance and JMockit doesn't complain about a missing #Injectable. If you need to mock some methods in call, it can be done with MockUp as usual.
new MockUp<Call>() {
#Mock
public void someMethodToMock() {
}
};
http://stackoverflow.com/questions/6645263/unit-testing-overridden-methods-which-call-super (This question has similar wording but is not the same)
I have something along the lines of:
public class SuperClass {
private int superClassInteger = 2;
public void superClassMethod() {
superClassInteger = 5;
}
public int getSuperClassInteger() {
return superClassInteger();
}
}
Then in my test I have:
public class SuperClassTest {
public void testSuperClassMethod() {
SuperClass superClass = new SuperClass();
superClass.superClassMethod();
assertEquals(5, super.getSuperClassInteger())
}
}
I then have a subclass:
public class SubClass {
private int subClassInteger = 2;
public void subClassMethod() {
super.superClassMethod();
subClassInteger = 32;
}
public int getSuperClassInteger() {
subClassInteger;
}
}
Then my test for the subclass:
public class SubClassTest {
public void testSubClassMethod() {
SubClass subClass = new SubClass();
subClass.subClassMethod();
assertEquals(5, subclass.getSuperClassInteger());
assertEquals(32, subclass.getSubClassInteger())
}
}
My problem is that to test the behavior of the subclass, I am repeating the test code I have for the super class. I could take out: assertEquals(5, subclass.getSuperClassInteger()); as I just want to test the business logic of the subclass. However, the problem with this is that if somebody accidentally removes the call to superClassMethod the test will still pass. So I need verify that a call to super is made. What is a common way of testing this use case?
Note: I know composition / strategy pattern vs inheritance helps solve this problem but for that to be the solution you are basically saying that I should NEVER override a method and invoke super in my code (which I find hard to believe there will never be a use for)
Use mockito spies. You can check for nearly any method call using that testing Framework.
https://github.com/mockito/mockito
This is probably not the answer you want (i.e not a workaround), but the answer you deserve but you should never override a method and invoke super.
I'm working on a legacy project that does that a lot, it's a nightmare to maintain, to debug and to test.
Instead, it's better to use an abstract class with a template method pattern:
Before
public class SuperClass<T> {
public void include(T t) {
validate(T);
dao.save(T);
}
// I've found code like that.
public void validate(T t) {
}
}
public class SubClass1 extends SuperClass<MyClass> {
#Override
public void include(MyClass mc) {
doStuff(mc);
doMoreStuff(mc);
super.include(mc);
}
#Override
public void validate(MyClass mc) {
doValidationStuff();
}
}
public class SubClass2 extends SuperClass<AnotherClass> {
#Override
public void include(AnotherClass ac) {
doDifferentStuff();
super.include(mc);
}
}
After
public abstract class AbstractClass<T> {
abstract void validate(T t);
// this method can now be tested
public void include(T t) {
validate(T);
dao.save(T);
}
}
public class Class1 extends AbstractClass<MyClass> {
public void validate(MyClass mc) {
doValidationStuff();
doStuff(mc);
doMoreStuff(mc);
}
}
public class Class2 extends AbstractClass<AnotherClass> {
public void validate(AnotherClass ac) {
doDifferentStuff();
}
}
As you can see, this refactoring simplifies maintenance and testing, you don't have to worry about having to mock the superclass method call in the Class1 and Class2 tests, and the code is closed to modification and open to extension, i.e, more maintainable.
Use JMockit and check the call to super with a Verification.
JMockit
Example for this
public void test {
SubClass subClass = new SubClass();
subClass.subClassMethod();
new Verifications() {
// mock only this method of superClass - and only in this test
#Mocked (methods = "superClassMethod")
SuperClass superClass;
{
superClass.superClassMethod();
times = 1; // specify invocation count
}
};
}
I'd like to avoid mocking the getClass() method for a class but cannot seem to find any way around it. I'm trying to test a class that stores objects class types in a HashMap to a particular method to be used later. A brief example of this is:
public class ClassToTest {
/** Map that will be populated with objects during constructor */
private Map<Class<?>, Method> map = new HashMap<Class<?>, Method>();
ClassToTest() {
/* Loop through methods in ClassToTest and if they return a boolean and
take in an InterfaceA parameter then add them to map */
}
public void testMethod(InterfaceA obj) {
final Method method = map.get(obj.getClass());
boolean ok;
if (method != null) {
ok = (Boolean) method.invoke(this, obj);
}
if (ok) {
obj.run();
}
}
public boolean isSafeClassA(final ClassA obj) {
// Work out if safe to run and then return true/false
}
public boolean isSafeClassB(final ClassB obj) {
// Work out if safe to run and then return true/fals
}
}
public interface InterfaceA {
void run()
}
public class ClassA implements InterfaceA {
public void run() {
// implements method here
}
}
public class ClassB implements InterfaceA {
public void run() {
// implements method here
}
}
I then have a JUnit test that looks a little like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest({ClassA.class})
public class ClassToTestTest {
private final ClassToTest tester = new ClassToTest();
#Test
public void test() {
MockGateway.MOCK_GET_CLASS_METHOD = true;
final ClassA classA = spy(new ClassA());
doReturn(ClassA.class).when(classA).getClass();
MockGateway.MOCK_GET_CLASS_METHOD = false;
tester.testMethod(classA);
verify(classA).run();
}
}
My problem is although inside the test() method classA.getClass(); will return ClassA, once inside tester's testMethod() method it still returns the ClassA$EnhancerByMockitoWithCGLIB$... class and so my object useful will always be null.
Is there any way I can get around mocking the class or what do I need to do to fix this?
Thanks in advance.
Your problem is actually that getClass is final in Object, so you can't stub it with Mockito. I can't think of a good way around this. There is one possibility, that you might consider.
Write a utility class that has a single method
public Class getClass(Object o){
return o.getClass();
}
and refactor the class that you're testing, so that it uses an object of this utility class, instead of calling getClass() directly. Then, make it possible to inject the utility object, either with a special package-private constructor, or with a setter method.
public class ClassToTest{
private UtilityWithGetClass utility;
private Map<Class<?>, Object> map = new HashMap<Class<?>, Object>();
public ClassToTest() {
this(new UtilityWithGetClass());
}
ClassToTest(UtilityWithGetClass utility){
this.utility = utility;
// Populate map here
}
// more stuff here
}
Now, in your test, make a mock of the object and stub getClass. Inject the mock into the class that you're testing.
Wow, what a headache to get this code testable. The main issues are that you can't use mock objects as key objects into your calls to map.get(obj.getClass()), and you're trying to invoke() potentially mock objects for your testing. I had to refactor your class under test so that we can mock out the functionality/behaviour and be able to verify its behaviour.
So this is your new implementation to be tested with member variables decoupling the various pieces of functionailty and injected by the test class
public class ClassToTest {
MethodStore methodStore;
MethodInvoker methodInvoker;
ClassToInvoke classToInvoke;
ObjectRunner objectRunner;
public void testMethod(InterfaceA obj) throws Exception {
Method method = methodStore.getMethod(obj);
boolean ok = false;
if (method != null) {
ok = methodInvoker.invoke(method, classToInvoke, obj);
}
if (ok) {
objectRunner.run(obj);
}
}
public void setMethodStore(MethodStore methodStore) {
this.methodStore = methodStore;
}
public void setMethodInvoker(MethodInvoker methodInvoker) {
this.methodInvoker = methodInvoker;
}
public void setObjectRunner(ObjectRunner objectRunner) {
this.objectRunner = objectRunner;
}
public void setClassToInvoke(ClassToInvoke classToInvoke) {
this.classToInvoke = classToInvoke;
}
}
This is your test class that no longer requires PowerMock, because it can't mock the Method class. It just returns a NullPointerException.
public class MyTest {
#Test
public void test() throws Exception {
ClassToTest classToTest = new ClassToTest();
ClassA inputA = new ClassA();
// trying to use powermock here just returns a NullPointerException
// final Method mockMethod = PowerMockito.mock(Method.class);
Method mockMethod = (new ClassToInvoke()).getClass().getMethod("someMethod"); // a real Method instance
// regular mockito for mocking behaviour
ClassToInvoke mockClassToInvoke = mock(ClassToInvoke.class);
classToTest.setClassToInvoke(mockClassToInvoke);
MethodStore mockMethodStore = mock(MethodStore.class);
classToTest.setMethodStore(mockMethodStore);
when(mockMethodStore.getMethod(inputA)).thenReturn(mockMethod);
MethodInvoker mockMethodInvoker = mock(MethodInvoker.class);
classToTest.setMethodInvoker(mockMethodInvoker);
when(mockMethodInvoker.invoke(mockMethod,mockClassToInvoke, inputA)).thenReturn(Boolean.TRUE);
ObjectRunner mockObjectRunner = mock(ObjectRunner.class);
classToTest.setObjectRunner(mockObjectRunner);
// execute test method
classToTest.testMethod(inputA);
verify(mockObjectRunner).run(inputA);
}
}
The additional classes you require are as follows
public class ClassToInvoke {
public void someMethod() {};
}
public class ClassA implements InterfaceA {
#Override
public void run() {
// do something
}
}
public class ClassToInvoke {
public void someMethod() {};
}
public class MethodInvoker {
public Boolean invoke(Method method, Object obj, InterfaceA a) throws Exception {
return (Boolean) method.invoke(obj, a);
}
}
public class MethodStore {
Map<Class<?>, Method> map = new HashMap<Class<?>, Method>();
public Method getMethod(InterfaceA obj) {
return map.get(obj);
}
}
Put all this into your IDE and it will pass with a Green bar...woohoo!
I've faced with similar question, too. I think you should add ClassToTest.class to #PrepareForTest, because you want to mock the getClass() function in that class