user5591691
user5591691

Reputation:

Mock Objects Created Inside method Under test to verify the arguments passed

Have a method as follows -

Class A
{

public void methodA(String zipcode)

{

  Country c= new Country(zipcode) 

}

}

Is it possible to verify using JUnit, that the country object got created with argument zipcode.

The test method will be somethig like

@Test
public void testMethod()
{
  A a = new A();  
  a.methodA("testCode");
}

Thanks

Upvotes: 2

Views: 2736

Answers (3)

daniu
daniu

Reputation: 14999

If you do need to test the call (as opposed to only its effects, what you can do is introducing a factory method in the tested class.

Class A {
    private Function<String,Country> createCountry = Country::new;
    public void methodA(String zipcode) {
          Country c= createCountry.apply(zipCode);
    }
}

Which you can then mock.

class ATest {
    @InjectMocks A sut;
    @Mock Function<String,Country> creator;

    @Test public void testCountryCreated() {
        String zipcode = "1234";

        Country country = mock(Country.class);
        when(creator.apply(zipcode)).thenReturn(country);

        sut.methodA(zipcode);

        verify(creator).apply(zipcode);
    }
}

Upvotes: 2

Hatice
Hatice

Reputation: 944

If you want to use PowerMockito you can do it easily like that

@RunWith(PowerMockRunner.class)
@PrepareForTest(X.class)
public class XTest {
        @Test
        public void test() {
                whenNew(MyClass.class).withNoArguments().thenThrow(new IOException("error message"));

                X x = new X();
                x.y(); // y is the method doing "new MyClass()"

                ..
        }
}

Use PowerMockito.verifyNew, e.g.

verifyNew(MyClass.class).withNoArguments();

Upvotes: 1

PotatoManager
PotatoManager

Reputation: 1775

You can try something like this.

public class MyClass {
static class Country{
    public Country(String zipcode){
        onCountryCreated();
    }
    public void onCountryCreated(){

    }
}

@Test
public static void test() {
    Country cntry = new Country("12345"){
        @Override
        public void onCountryCreated(){
            System.out.println("Created");
            //assert true;
        }
    };
}
}

Upvotes: 0

Related Questions