I'm using TestNG for testing and JMockit for mocking mockMethod(). Here's the test case:
#Test
public void testClass1() {
new MockUp<MyInterface>() {
#Mock
public int myMethod(final MyObject someObject ){
return 0;
}
};
MyObject obj = new MyObject();
Assert.assertEquals(obj.mockMethod(someObject),0);
}
}
The mockMethod() I'm calling for assertEquals() looks like this:
public class Class1 {
MyInterface my;
public int mockMethod(final MyObject someObject ){
...... //processing steps
return my.myMethod(someObject);
}
}
Test case throws a Null pointer exception. What am I doing wrong? Do I mock the implementation of mockMethod()? I tried that too, but it hasn't worked.
JMockit created a mock instance of MyInterface, but your test never used it. It can be obtained through the MockUp#getInstance() method. Then of course the test also needs to pass the instance to the class under test.
Related
I have a class with a rest end point like:
#Path("/myPath/myFunction")
public class MyClass {
#Get
#Path("someSpecificFunction")
public Response getSomeData(#QueryParam("myVar") String myVar) {
MyObject myObject = new MyObject();
JsonObject response = myObject.getJson(myVar);
return Response.ok(response.toString()).build();
}
}
I want to write a unit test for getSomeData and want to mock myObject.getJson call.
What is the best way to do this?
I want to avoid #PrepareForTest on MyClass if possible.
I tried converting creation of MyObject instance to a static method like:
protected static MyObject createMyObject() {
return new MyObject();
}
But PowerMockito requires #PrepareForTest even for mocking or static methods.
How do I solve this?
You can use PowerMocktio using whenNew()
, Steps
PrepareForTest MyClass
Use whenNew which means when a new object is instantiated, the use this mocked one
#RunWith(PowerMockRunner.class)
#PrepareForTest(MyClass.class)
public class ExampleClassTest {
private MyClass myClass;
#Before
public void setUp() {
myClass = new MyClass();
}
#Test
public void shouldDoSomething() {
MyObject mocked = mock(MyObject.class);
PowerMockito.whenNew(String.class).withNoArguments().thenReturn(mocked);
assertEquals("mocked", myClass.getString());
}
Another option is to change the design of the class and having the test injecting MyObject
Something like
public MyClass {
MyObject myObject = new MyObject()
public method(){
...
}
}
MyClassTest {
#Test
public test() {
MyClass myClass = new MyClass();
myClass.myObject = mock(MyObject.class);
//test code
}
}
This simplify testability and can work with any framework, also if you have a DI framework will help introducing it.
I am trying to write a test for pre-existing class.
class ClassToBeTested {
private final Obj1 a;
ClassToBeTested(String anotherVariable) {
a = new Obj1(anotherVariable);
}
public void methodToBeTested() {
if(invokeSomeOtherMethod()) {
a.getAnotherVariable().doSomething();
}
}
public boolean invokeSomeOtherMethod() {
// return true or false based on some logic
}
Obj1 getObj1() {
return a;
}
}
Below is my Test Class:
class TestClass {
#Test
public void testMethod() {
ClassToBeTested x = new ClassToBeTested("someString");
ClassToBeTested spyX = spy(x);
doReturn(false).when(spyX).invokeSomeOtherMethod();
spyX.methodToBeTested();
verify(spyX, times(1)).getObj1().doSomething();
}
}
This is my understanding:
Since the obj1 is private final object which is created in the class constructor, it neither be directly accessed in the test method nor force the spyObject to use a mocked version of obj1.
Also since verify() requires mocked version of obj1, it throws me an error:
Wanted But Not invoked: x.getObj1(), however there are otherInteractions with this mock: x.invokeSomeOtherMethod()
Is my understanding wrong? What would be the way to test testMoethod()?
You seem to not understand how to do proper dependency injection. You don't need to change all your code in order to make it easier to test - just use constructor telescoping for example:
class ClassToBeTested {
private final Obj1 a;
public ClassToBeTested(String anotherVariable) {
this(new Obj1(anotherVariable));
}
ClassToBeTested(Obj1 a) {
this.a = a;
}
Done. Now you have a package-protected constructor that you can use to insert an instance of a directly. And all your other production code can stay like it is.
In other words: don't "fix" your design problems by using mocking framework tricks.
[10/7/06 4:00 Edited example code]
I'm trying to test some code (using JMockIt with TestNG) without touching the database, but it appears a mocked method is still actually called. Here's the simplified setup:
class DBRow {
public DBRow() { }
public DBRow(Object obj) {
initialize(obj);
}
public void insert() {
actuallyAddRowToDatabase();
}
}
class MyObject extends DBRow {
MyObject(Object obj) {
super(obj);
}
public void insert(Object obj) {
doSomething(obj);
insert();
}
}
class Factory {
static MyObject createObject(Object obj1, Object obj2) {
MyObject newObj = new MyObject(obj1);
newObj.insert(obj2);
return newObj;
}
}
I wanted to mock the insert operation to prevent an insertion in the actual database, so I tried something like this:
#Test
public void testCreation() {
new Expectations(MyObject.class) {
MyObject mock = new MyObject(null) {
#Mock
public void insert(Object obj) { }
};
{
new MyObject(anyString); result = mock;
}};
MyObject test = Factory.createObject("something", "something else");
}
But it appears that the real insert(Object) is still being called. I'm specifying that the class is mocked so all instances should be mocked, right? And I'm specifying that the insert method should be mocked, so why would the real method be getting called?
There's also a second problem with the above. When I define the mock class inside the Expectations block (as above), it seems that only the Row() constructor is being called instead of Row(Object), and thus the object is not correctly initialized. I fixed this by moving it into a #BeforeTest method and instantiating the class there. Here's what that looks like:
private MyObject mock;
#BeforeTest
public void beforeTest() {
new MockUp<MyObject>() {
#Mock
public void insert(Object obj) { }
};
mock = new MyObject("something");
}
#Test
public void testCreation() {
new Expectations(MyObject.class) {{
new MyObject(anyString); result = mock;
}};
MyObject test = Factory.createObject("something", "something else");
}
So this seems to get the correct constructor to be called, but it still seems that insert() is being called as well. Any insights?
You are not using mocked object to call your fucntion i.e. private MyObject mock; but a real object test,
MyObject test = new MyObject("something", "something else");
Call testStuff() on mockinstead of test.
All instances wouldn't be automatically mocked, you have to work with mocked instances.
I was finally able to write my tests such that the right constructor got called and no actual database operation occurred. I think part of the problem I was bumping into was that one of the methods in the Expectations block was getting a different object than I expected for a parameter I wasn't interested in. And I think the other part of my problem was mixing up the roles of a MockUp class and Expectations recordings.
The code under test didn't change. Here's my simplified example again for convenience:
class DBRow {
public DBRow() { }
public DBRow(Object obj) {
initialize(obj);
}
public void insert() {
actuallyAddRowToDatabase();
}
}
class MyObject extends DBRow {
MyObject(Object obj) {
super(obj);
}
public void insert(Object obj) {
doSomething(obj);
insert();
}
}
class Factory {
static MyObject createObject(Object obj1, Object obj2) {
MyObject newObj = new MyObject(obj1);
newObj.insert(obj2);
return newObj;
}
}
Here's essentially what I ultimately ended up with for test code:
Object something;
Object somethingElse;
#BeforeTest
public void beforeTest() {
new MockUp<MyObject>() {
#Mock
public void insert() { } // override the "actual" DB insert
}; // of Row.insert()
}
#Test
public void testCreation() {
MyObject mock = new MyObject(something); // object correctly init'd
// by Row.initialize(Object)
new Expectations(MyObject.class) {{
new MyObject(something); result = mock;
mock.insert(somethingElse);
}};
MyObject test = Factory.createObject(something, somethingElse);
}
The key points were that A) I created a MockUp class to override the DB operations, and B) created a local instance of that partially mocked instance to record my Expectations.
This is base of my tested class:
public class MyClass {
public void myMethod() {
if (condition) {
Message message = null;
throw new MyException(message.getMessgae()); // throws NullPointerException
}
}
}
I would like test class over, whether myMethod throws MyException. message is null in test instance, because in another use instances spring bean from properties file, where value exists.
Because message returns NullPointerException, myTest not passed:
public class MyClassTest {
#Test
public void testMyMethod() {
try {
MyClass myClass = new MyClass();
myClass.myMethod();
fail;
} catch(MyException e) {
}
}
}
My idea is create mock of MyException or crate mock of message.getMessgae() if it is possible. Bud I don't know how...
I think you want to use PowerMockito to mock the parameterized constructor of MyException used in MyException(message.getMessage()) such that the constructor doesn't actually try to invoke getMessage() on the null object.
That setup is explained in detail here.
I am writing an unit testing using JUNIT + Mockito to test a method like :
public someObject methodUnderTest(){
SomeObject obj = SomeAbstractClass.someMethod();
if(obj!=null){
obj.someOtherMethod();
}
return someThing;
}
And I would like to mock the call on abstract Class "SomeAbstractClass" mentioned in above code fragment so i can verify call on "obj" like :
verify(SomeAbstractClass).someMethod();
verify(obj).someOtherMethod();
I have tried using mockito features like :
Mockito.CALLS_REAL_METHODS
Mockito.RETURNS_MOCKS
but they don't work due to dependencies not available to the SomeAbstractClass.
Note:
1) SomeObject is an Interface.
2) I need a technique to test above code fragment. I am constrained to use the above code fragment and cannot change the code fragment.
You can use PowerMock to mock static and final methods.
It sounds like the problem is that your use of CALLS_REAL_METHODS is applying to the entire class, where you really want to mock out specific methods (i.e. make a "partial mock"). You have two options here, one using thenCallRealMethod, and one using CALLS_REAL_METHODS and then specifically mocking the calls you need:
public void testMethodUnderTest_mockSpecificThings() {
SomeAbstractClass myAbstractClass = Mockito.mock(SomeAbstractClass.class);
SomeAbstractClass myObject = Mockito.mock(SomeObject.class);
when(myAbstractClass.someMethod()).thenReturn(foo);
when(myAbstractClass.methodUnderTest()).thenCallRealMethod();
myAbstractClass.methodUnderTest();
verify(myAbstractClass).someMethod();
verify(myObject).someOtherMethod();
}
public void testMethodUnderTest_makeSpecificRealCalls() {
SomeAbstractClass myAbstractClass =
Mockito.mock(SomeAbstractClass.class, CALLS_REAL_METHODS);
SomeAbstractClass myObject = Mockito.mock(SomeObject.class);
// overrides the default answer
when(myAbstractClass.someMethod()).thenReturn(myObject);
myAbstractClass.methodUnderTest();
verify(myAbstractClass).someMethod();
verify(myObject).someOtherMethod();
}
Be forewarned that SomeAbstractClass is never actually instantiated, so if you rely on any behavior in the abstract class constructor, like variable initialization--including inline initialization where the fields are declared--you will need to make those calls explicitly yourself.
Assumption: if you write unit test, I guess you still can modify tested method a bit.
Solution:
extract static method call to overridable method:
public someObject methodUnderTest() {
SomeObject obj = getSomeObject();
if(obj!=null){
obj.someOtherMethod();
}
return someThing;
}
protected SomeObject getSomeObject() {
return SomeAbstractClass.someMethod();
}
then you can use Mockito Spy to partially mock the object you actually test:
private ClassUnderTest classUnderTest;
#Before
public void setUp() {
classUnderTest= new ClassUnderTest();
classUnderTest = Mockito.spy(classUnderTest);
}
#Test
public void test() {
SomeObject someObject = Mockito.mock(SomeObject.class);
when(classUnderTest.getSomeObject()).thenReturn(someObject);
classUnderTest.methodUnderTest();
verify(someObject).someOtherMethod();
}
#Test
public void testNull() {
when(classUnderTest.getSomeObject()).thenReturn(null);
classUnderTest.methodUnderTest();
verify(something);
}
Use anonymous classes:
public interface SomeObject {
public Object someOtherMethod();
}
public abstract class SomeAbstractClass {
abstract SomeObject someMethod();
}
#Test
public void test() {
SomeAbstractClass target = new SomeAbstractClass() {
SomeObject someMethod() {
// some impl
SomeObject someObject = new SomeObject() {
public Object someOtherMethod() {
// some other impl
}
};
return someObject;
}
};
// now test target
}