'How to handle a object argument to a method when it is typecasted to other in junit
I am new to Junit and got stuck with below usecase for multiple test classes which need to be covered for code coverage. Please help me out for the same. Usecase:
public interface InputRequest {
public String getUserName();
}
public class WebRequest implements inputRequest {
//definition
pubic String getProductById(int productId) {
//definition
}
}
public class mainClass {
public void methodA(InputRequest inputRequest) {
//some definition
String userName = inputRequest.getUserName();
WebRequest webRequest = (WebRequest) inputRequest;
String productName = webRequest.getProductById(123);
//remaining definition
}
}
@RunWith(PowerMockRunner.class)
public class TestMainClass() {
@Mock
WebRequest webRequest;
@Mock
InputRequest inputRequest;
@Test
public void testMethod() {
TestMainClass testMainClass = new TestMainClass();
Mockito.When(testMainClass.methodA(inputRequest).thenReturn("somevalue");
}
}
While writing junit for methodA() in mainClass, I am getting a NullPointerException when I am passing WebRequest as an argument to methodA() and getting ClassCastException when passing inputRequest as an argument to methodA() and mocking those respective objects.
Please suggest me how to test this use case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
