In class A, i got a function called updateAttribute. In class B, I got a junit test, which stores during execution this function in a Method object (code is simplified).
public class A {
public Optional<AttributeObject> updateAttribute(
#ApiParam("Qual of attribute") #PathParam("qual") #Qual final String qual,
#NotNull #Valid final UpdateObject a) {
// here, I've cut a few lines of code
return null;
}
}
public class ATest extends AnotherTest {
#Test
public void someTest()
throws NoSuchMethodException, SecurityException {
try (
// some code I've cut
final Method method =
A.getClass().getMethod("updateAttribute", String.class, UpdateObject.class);
// some code I've cut
}
}
}
The junit test fails at this call of .getMethod() with:
java.lang.IllegalArgumentException: HV000181: Wrong number of
parameters. Method or constructor
java.util.Optional"<"packageName.A">"#updateAttribute(String,
UpdateObject) expects 1 parameters, but got 2.
(...)
When I change the call to
final Method method =
A.getClass().getMethod("updateAttribute", String.class);
or similar, the trace just claims - as expected - that this method doesn't exist.Any ideas how to fix this?
Not an answer, just content that doesn't fit into a comment.
Reduced the code to this:
#Test
public void someTest()
throws NoSuchMethodException, SecurityException {
final Method method =
A.class.getMethod("updateAttribute", String.class, Integer.class);
}
}
class A {
public Optional<String> updateAttribute(
final String qual, Integer a) {
return null;
}
}
And that works fine.
Not reproducable.
Related
I have a class which I would like to test with a public static method that contains some chained method calls. Assuming that an exception occurs during the chained method calls, how do I handle this effectively and make it return some specific value?
Following is the code sample of the test class.
#RunWith(PowerMockRunner.class)
#PrepareForTest({CodeWithPrivateMethod.class,CodeWithAnotherPrivateMethod.class,CodeWithYetAnotherPrivateMethod.class})
public class CodeWithPrivateMethodTest {
#Test
public void when_gambling_is_true_then_always_explode() throws Exception {
CodeWithYetAnotherPrivateMethod codeWithYetAnotherPrivateMethod = PowerMockito.spy(new CodeWithYetAnotherPrivateMethod());
PowerMockito.whenNew(CodeWithYetAnotherPrivateMethod.class).withAnyArguments().thenReturn(codeWithYetAnotherPrivateMethod);
CodeWithAnotherPrivateMethod codeWithAnotherPrivateMethod = PowerMockito.spy(new CodeWithAnotherPrivateMethod());
PowerMockito.whenNew(CodeWithAnotherPrivateMethod.class).withAnyArguments().thenReturn(codeWithAnotherPrivateMethod);
PowerMockito.doReturn(true).when(codeWithYetAnotherPrivateMethod, "getGambling");
//PowerMockito.doReturn(codeWithYetAnotherPrivateMethod).when(codeWithAnotherPrivateMethod, "getGambleValue");
PowerMockito.spy(CodeWithPrivateMethod.class);
CodeWithPrivateMethod.startGamble();
}
}
Following is the code sample for the class under test
public class CodeWithPrivateMethod {
public static void startGamble() {
Boolean gamble = CodeWithAnotherPrivateMethod.getGambleValue()
.getGambling();
if (gamble) {
System.out.println("kaboom");
}else{
System.out.println("boom boom");
}
}
}
Following is the code sample for the class that gets called from the class under test
public class CodeWithAnotherPrivateMethod {
static CodeWithYetAnotherPrivateMethod codeWithYetAnotherPrivateMethod = new CodeWithYetAnotherPrivateMethod();
public static CodeWithYetAnotherPrivateMethod getGambleValue() {
return codeWithYetAnotherPrivateMethod; //works fine
return null; // fails
}
}
Following is the code sample for the other class that gets called from the class under test
public class CodeWithYetAnotherPrivateMethod {
public Boolean getGambling() {
return false;
}
}
So Assuming I return a null value from getGambleValue() method of CodeWithAnotherPrivateMethod class, how do I handle this null value effectively in my testclass?
This is how to specify expected exceptions using Mockito:
#Test(expected = NullPointerException.class)
public void when_gambling_is_true_then_always_explode() throws Exception {
...
Before I found out about this I would do:
#Test
public void when_gambling_is_true_then_always_explode() throws Exception {
// setup omitted
try {
CodeWithPrivateMethod.startGamble();
}
catch(NullPointerException e) {
// expected
return;
}
fail("Expected NullPointerException");
}
EDIT: Testing multiple classes that call each other statically like this is a severe code smell. Unit tests should test a single class and inline static calls should be limited to utility classes.
Another comment: your example class names are very confusing. Next time please stick with Foo, Bar, Baz or Appple, Pear, Banana.
If you are not getting an NPE then I expect your mocking/spying is interfering. If you call the code under test without mocking/spying the call chain would be:
CodeWithPrivateMethod.startGamble();
->
CodeWithYetAnotherPrivateMethod value = CodeWithAnotherPrivateMethod.getGambleValue();
->
return null;
<-
value.getGambling();
<- throws NullPointerException
What exactly are you trying to find out or achieve?
EDIT: Here's how it should work with PowerMock
#RunWith(PowerMockRunner.class)
#PrepareForTest(CodeWithAnotherPrivateMethod.class)
public class CodeWithPrivateMethodTest {
#Mock
private CodeWithYetAnotherPrivateMethod yetAnotherInstance;
#Test
public final void testStartGamble() {
// SETUP
mockStatic(CodeWithAnotherPrivateMethod.class);
expect(CodeWithAnotherPrivateMethod.getGambleValue())
.andReturn(yetAnotherInstance);
Boolean gamblingValue = true;
expect(yetAnotherInstance.getGambling()).andReturn(gamblingValue);
replayAll();
// CALL
CodeWithPrivateMethod.startGamble();
// VERIFY
verifyAll();
}
Consider the following code:
#Tested
CodeToTest codeToTest;
#Injectable
Injected injected;
#Test
public void test() {
new Expectations() {{ ... }}
assertThat(codeToTest.memberVariable).isEqualTo("x");
}
//
public class CodeToTest { public CodeToTest(Injected injected) { memberVariable = injected.getProperty("x") } }
I want to test CodeToTest. CodeToTest needs Injected to be injected into it's constructor. How do I set a property such as injected.setProperty("x") so that it is available for access in CodeToTest?
The test at hand should be covering a specific method of CodeToTest; the constructor should have its own tests like your test does. So for example, if the constructor is setting a field according to what gets passed in, like this:
public class Bar {
public int getValue() {
return 8675309;
}
}
public class Foo {
public String field = null;
public Foo(Bar b) {
this.field = "" + b.getValue();
}
public String getField() {
return this.field;
}
public char getFirstChar() {
return getField().charAt(0);
}
}
Here I am setting a String field according to an int found in a Bar that was passed into the constructor. I wish to unit test my getFirstChar() method ...
#Tested Foo foo;
#Injectable Bar bar;
#Test
public void test() throws Exception {
// ...
}
Now, as you point out, in this case my field has already been set before test() even starts. So I have two choices here: Firstly, since I am pulling out the field based on its getter, I can partially mock my class being tested:
#Test
public void test() throws Exception {
new Expectations(foo) {{
foo.getField(); result = "24601";
}};
char c = foo.getFirstChar();
assertThat(c, is('2'));
}
OR, if you don't want to do this or if you are doing direct field access rather than via getter, you can use Deencapsulation (part of JMockit) to set the internal field and then test:
#Test
public void test() throws Exception {
Deencapsulation.setField(foo, "field", "24601");
char c = foo.getFirstChar();
assertThat(c, is('2'));
}
And of course, I test my constructor separately:
#Test
public void testConstructor() throws Exception {
new Expectations() {{
bar.getValue(); result = 24601;
}};
Foo foo2 = new Foo(bar);
String fieldValue = foo2.getField(); // or use Deencapsulation
assertThat(fieldValue, is("24601"));
}
Hope this helps, and good luck!
I have a problem when writing unit testing with mock. There is a object which I need to mock have a lot getter, which I do call them at the code. However, those are not the purpose of my unit test. So, is there is a way I can mock all the methods instead of mock them one by one.
Here is the code example:
public class ObjectNeedToMock{
private String field1;
...
private String field20;
private int theImportantInt;
public String getField1(){return this.field1;}
...
public String getField20(){return this.field20;}
public int getTheImportantInt(){return this.theImportantInt;}
}
and this is the service class I need to test
public class Service{
public void methodNeedToTest(ObjectNeedToMock objectNeedToMock){
String stringThatIdontCare1 = objectNeedToMock.getField1();
...
String stringThatIdontCare20 = objectNeedToMock.getField20();
// do something with the field1 to field20
int veryImportantInt = objectNeedToMock.getTheImportantInt();
// do something with the veryImportantInt
}
}
within the test class, the test method is like
#Test
public void testMethodNeedToTest() throws Exception {
ObjectNeedToMock o = mock(ObjectNeedToMock.class);
when(o.getField1()).thenReturn(anyString());
....
when(o.getField20()).thenReturn(anyString());
when(o.getTheImportantInt()).thenReturn("1"); //This "1" is the only thing I care
}
So, is there a way that I can avoid writing all the "when" for the useless "field1" to "field20"
You can control the default answers of your mock. When you're creating the mock, use:
Mockito.mock(ObjectNeedToMock.class, new Answer() {
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
/*
Put your default answer logic here.
It should be based on type of arguments you consume and the type of arguments you return.
i.e.
*/
if (String.class.equals(invocation.getMethod().getReturnType())) {
return "This is my default answer for all methods that returns string";
} else {
return RETURNS_DEFAULTS.answer(invocation);
}
}
}));
If you're not interested in the result of getField1() to getField20() in a particular test case, you shouldn't mock it at all. In other words, if all the specific test case should be concerned about is getTheImportantInt(), then your test case should look like this:
#Test
public void testMethodNeedToTest() throws Exception {
ObjectNeedToMock o = mock(ObjectNeedToMock.class);
when(o.getTheImportantInt()).thenReturn("1");
// test code goes here
}
For kotlin users:
val mocked:MyClassToMock = Mockito.mock(MyClassToMock::class.java,
object:Answer<Any> {
override fun answer(invocation: InvocationOnMock?): Any {
if (String::class.java.equals (invocation?.method?.getReturnType())) {
return "Default answer for all methods that returns string";
} else {
return Mockito.RETURNS_DEFAULTS.answer(invocation);
}
}
})
Using jmockit 1.2 jar,
Trying to mock String's length method but getting Unexpected Invocation Exception:
FAILED: test
java.lang.IllegalStateException: Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter
at StringDemo.TestA$1.<init>(TestA.java:17)
at StringDemo.TestA.test(TestA.java:13)
I am using testNG:
#Test
public void test() throws Exception
{
new Expectations()
{
#Mocked("length")
String aString;
{
aString.length();
result = 2;
}
};
System.out.println(A.showA("test"));
}
}
Actual class A:
public class A {
public static int showA(String str){
int a= str.length();
return a;
}
}
This is the wrong way of recording the expected results. You shouldn't mock and record String's length() method, record your showA() instead. here is the solution
#SuppressWarnings("unused")
#Test
public void test() throws Exception
{
new Expectations()
{
#NonStrict
final Source mock = null;
{
Source.showA(anyString);
result = 2;
}
};
assertEquals(2, Source.showA("test"));
}
I have been trying to run the following test using mockito and junit and I keep on getting "java.lang.NullPointerException: name must not be null"
Can anyone tell me why this is happening?
On debugging, I found out that this exception is thrown when the test executes the following statement in isStopValid(String) method:
FacilityValidationUtil facUtil = new FacilityValidationUtil();
#RunWith(MockitoJUnitRunner.class)
public class MyFormTest{
#InjectMocks MyForm form = new MyForm();
#Mock FacilityValidationUtil facUtil;
#Test
public void testIsStopValid() throws FinderException{
when(facUtil.isFacilityValid("")).thenReturn(false);
form.setOrigin("");
assertEquals(false, form.isStopValid(form.getOrigin()));
}
}
Class with method to be tested:
public class MyForm{
FacilityValidationUtil facUtil = new FacilityValidationUtil();
public boolean isStopValid(String stop){
try {
return facUtil.isFacilityValid(stop);
} catch (FinderException e) {
log.error("Error finding the stop. "+e.getCause());
return false;
}
}
}
public class FacilityValidationUtil{
private FacilityDAO facilityDao = new HibernateFacilityDAO();
public boolean isFacilityValid(String facility) throws FinderException{
boolean test;
FacilityImpl facilityImpl = facilityDao.findFacilityByNassCode(facility);
test = (facilityImpl==null)?false : true;
return test;
}
}
public class HibernateFacilityDAO extends HibernateAbstractDeltaDAO implements FacilityDAO {
public HibernateFacilityDAO() {
super(false);
}
}
Short Answer: You are trying to mock a variable (facUtil) that is local to your isStopValid method, so the mock version of this object in your test is never going to be called because you are 'newing it up" each time.
Long Answer: It looks like you are trying to mock the call to your FacilityValidationUtil class, and if this is the case, then you need to either make the class a field so that Mockito can inject the object by reflection (if this object is thread safe, which it looks like it is) or explore a mocking framework like PowerMockito that will allow you to mock a constructor (google for PowerMockito when new).
PowerMockito.whenNew(FacilityValidationUtil.class).withNoArguments().thenReturn(facUtil);
Mockito doesn't support any mocking of constructor args by default.
EDIT
If you are still having trouble, then I would suggest starting with a smaller example. I've put together one for you that works and uses the code you are trying to test (It's using inner classes though, which Mockito has some quirky rules about, but I'm just doing it to compress the example).
#RunWith(MockitoJUnitRunner.class)
public class MyFormTest {
#InjectMocks
private MyForm form = new MyForm();
#Mock
private FacilityValidationUtil facUtil;
#Test
public void testIsStopValid_false() {
when(facUtil.isFacilityValid("")).thenReturn(false);
assertEquals(false, form.isStopValid(""));
}
#Test
public void testIsStopValid_true() {
when(facUtil.isFacilityValid("")).thenReturn(true);
assertEquals(true, form.isStopValid(""));
}
public class MyForm {
private FacilityValidationUtil facUtil = new FacilityValidationUtil();
public boolean isStopValid(String stop) {
try {
return facUtil.isFacilityValid(stop);
} catch (FinderException e) {
return false;
}
}
}
public class FacilityValidationUtil {
public boolean isFacilityValid(String facility) throws FinderException {
throw new RuntimeException(facility);
}
}
public class FinderException extends RuntimeException {
public FinderException(String message) {
super(message);
}
}
}
What's really important is that your mock is not getting injected correctly. Until you get that resolved, you are going to keep getting the same error. Set a break point in your MyForm at the point you call facUtil.isFaciltyValid and look at the object. It should be a mockito object, not your class.
Good luck.