How to mock exception in unmocked class - java

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.

Related

TestNG interceptTestClassConstructor analog

I need somehow to intercept Test class constructor to override a behavior. In JUnit, it is done with:
#Override
public <T> T interceptTestClassConstructor(Invocation<T> invocation,
ReflectiveInvocationContext<Constructor<T>> invocationContext,
ExtensionContext extensionContext) throws Throwable {
...
}
How is this achievable in TestNG?
You could override the behavior using IObjectFactory.
public class CustomObjectFactory implements IObjectFactory {
#Override
public Object newInstance(Constructor constructor, Object... params) {
if(constructor.getDeclaringClass().equals(YourTestCalss.class)) {
return yourCustomObject();
}
try {
return constructor.newInstance(params);
} catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// error handling...
}
return null; // or any other object or throw exception
}
}
Now in a test class, add a method as below:
#Test
public class YourTestClass {
// ......
// test methods
// ......
#ObjectFactory
public ITestObjectFactory getObjectFactory() {
return new CustomObjectFactory();
}
}
Please note that even though this method is declared inside YourTestClass, this same object factory would be used for every other test class in your suite. Hence the if condition to check the class is required in CustomObjectFactory.newInstance.
You may also try IObjectFactory2 which has a newInstance method taking Class as the parameter.
TestNG has an implementation for IObjectFactory -> ObjectFactoryImpl.
You could use extends ObjectFactoryImpl instead, in which case the code within the `newInstance could be:
if(constructor.getDeclaringClass().equals(YourTestCalss.class)) {
return yourCustomObject();
}
return super.newInstance(constructor, params);
BUT note that, Since ObjectFactoryImpl is inside the testng.internal package, I assume that extending ObjectFactoryImpl is not recommended.
As discuss in mailing group, #KrishnanMahadevan fixed a bug which will allow to intercept Test class constructor in version 7.5
public class LocalSuiteAlteringListener implements IAlterSuiteListener {
#Override
public void alter(List<XmlSuite> suites) {
suites.forEach(each -> each.setObjectFactoryClass(MyFactory.class));

Null Pointer Exception in mocking Interface method

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.

How to replace method invocation with mock?

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());
}
}

Mocking a call on a public method of an abstract class without subclassing the abstract Class, using mockito prefererably

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
}

java.lang.IllegalStateException: missing behavior definition for the preceding method call getMessage("title")

I'm using EasyMock(version 2.4) and TestNG for writing UnitTest.
I have a following scenario and I cannot change the way class hierarchy is defined.
I'm testing ClassB which is extending ClassA.
ClassB look like this
public class ClassB extends ClassA {
public ClassB()
{
super("title");
}
#Override
public String getDisplayName()
{
return ClientMessages.getMessages("ClassB.title");
}
}
ClassA code
public abstract class ClassA {
private String title;
public ClassA(String title)
{
this.title = ClientMessages.getMessages(title);
}
public String getDisplayName()
{
return this.title;
}
}
ClientMessages class code
public class ClientMessages {
private static MessageResourse messageResourse;
public ClientMessages(MessageResourse messageResourse)
{
this.messageResourse = messageResourse;
}
public static String getMessages(String code)
{
return messageResourse.getMessage(code);
}
}
MessageResourse Class code
public class MessageResourse {
public String getMessage(String code)
{
return code;
}
}
Testing ClassB
import static org.easymock.classextension.EasyMock.createMock;
import org.easymock.classextension.EasyMock;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ClassBTest
{
private MessageResourse mockMessageResourse = createMock(MessageResourse.class);
private ClassB classToTest;
private ClientMessages clientMessages;
#Test
public void testGetDisplayName()
{
EasyMock.expect(mockMessageResourse.getMessage("ClassB.title")).andReturn("someTitle");
clientMessages = new ClientMessages(mockMessageResourse);
classToTest = new ClassB();
Assert.assertEquals("someTitle" , classToTest.getDisplayName());
EasyMock.replay(mockMessageResourse);
}
}
When I'm running this this test I'm getting following exception:
java.lang.IllegalStateException: missing behavior definition for the preceding method call getMessage("title")
While debugging what I found is, it's not considering the mock method call
mockMessageResourse.getMessage("ClassB.title") as it has been called from the construtor (ClassB object creation).
Can any one please help me how to test in this case.
Thanks.
You need to call EasyMock.replay(mock) before calling the method under test. After calling the method under test you can call EasyMock.verify(mock) to verify the mock is called.
Next you need to add another expect call with the "title" argument since you call it twice.
Code:
EasyMock.expect(mockMessageResourse.getMessage("title")).andReturn("title");
EasyMock.expect(mockMessageResourse.getMessage("ClassB.title")).andReturn("someTitle");
EasyMock.replay(mockMessageResourse);
clientMessages = new ClientMessages(mockMessageResourse);
classToTest = new ClassB();
Assert.assertEquals("someTitle" , classToTest.getDisplayName());
EasyMock.verify(mockMessageResourse);
In my case, it was caused by the omission of a return value specification (andReturn(...)).
http://www.smcmaster.com/2011/04/easymock-issue-1-missing-behavior.html for more details.
This can have various causes (someMock is the name of your mocked Object in this answer).
On the one side it can be that you need to expect the call via
expect(someMock.someMethod(anyObject()).andReturn("some-object");
like in Reda's answer.
It can also be that you forgot to call replay(someMock) before you used the mock, like you can see in Julien Rentrop's answer.
A last thing that is possible that wasn't mentioned here is that you used the mock somewhere else before in a test and forgot to reset the mock via reset(someMock).
This can happen if you have multiple Unit Tests like this:
private Object a = EasyMock.createMock(Object.class);
#Test
public void testA() throws Exception {
expect(a.someThing()).andReturn("hello");
replay(a);
// some test code and assertions etc. here
verify(a);
}
#Test
public void testB() throws Exception {
expect(a.someThing()).andReturn("hello");
replay(a);
// some test code and assertions etc. here
verify(a);
}
This will fail on one test with the IllegalStateException, because the mock a was not reset before being used in the next test. To solve it you can do the following:
private Object a = EasyMock.createMock(Object.class);
#Test
public void testA() throws Exception {
expect(a.someThing()).andReturn("hello");
replay(a);
// some test code and assertions etc. here
verify(a);
}
#Test
public void testB() throws Exception {
expect(a.someThing()).andReturn("hello");
replay(a);
// some test code and assertions etc. here
verify(a);
}
#After
public void tearDown() throws Exception {
reset(a); // reset the mock after each test
}
You should put your call to replay after the expect calls, and before you use your mock. In this case you should change your test to something like this:
#Test
public void testGetDisplayName()
{
EasyMock.expect(mockMessageResourse.getMessage("ClassB.title")).andReturn("someTitle");
EasyMock.replay(mockMessageResourse);
clientMessages = new ClientMessages(mockMessageResourse);
classToTest = new ClassB();
Assert.assertEquals("someTitle" , classToTest.getDisplayName());
}
For me, this exception was occurring because the method I was trying to stub was final (something I hadn't realized).
If you want to stub a final method you'll need to use Powermock.

Categories