Home > Net >  How to write unit test for void method with for loop and utilization of method from another class?
How to write unit test for void method with for loop and utilization of method from another class?

Time:06-08

I have a void method in the following format, and I am struggling with how to test it. Thanks for your comments and help!

public class A {
    @NonNull
    B b;

    @NonNull
    C c;
   
    public void a(String region){
        for (M m: M.getMarketplacesForRegion(REGION_MAP.get(region))) {
            b.initialize(CONSTANT, m.getId());
            b.initialize(c   CONSTANT, m.getId());
        }  
    } 
}

CodePudding user response:

You could use a mocking framework like Mockito, EasyMock or PowerMock and create a mock for B, which you then assign to b in the instance of the class you want to test.

You can tell the mock which methods you expect to have called, which parameters you expect to be passed and then you can verify that all your expectations were fulfilled.

See the respective framework's documentation for an example of how to use them.

  • Related