How mock private method that modify private variables?

后端 未结 3 1454
醉梦人生
醉梦人生 2021-01-13 14:07

How mock private method that modify private variables?

class SomeClass{
    private int one;
    private int second;

    public SomeClass(){}

    public in         


        
3条回答
  •  借酒劲吻你
    2021-01-13 14:27

    Provided the fact that other answers are pointing out that such test cases are brittle and that the test cases should not be based on implementation and should be dependent on the behavior if you still want to mock them then here are some ways:

    PrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class,
                                    "sayIt", String.class);
    String expected = "Hello altered World";
    expectPrivate(tested, "sayIt", "name").andReturn(expected);
    replay(tested);
    String actual = tested.say("name");
    verify(tested);
    assertEquals("Expected and actual did not match", expected, actual);
    

    This is how you would do it with PowerMock.

    expectPrivate() of PowerMock does this.

    Test cases from PowerMock which test the private method mocking

    UPDATE: Partial Mocking with PowerMock there are some disclaimers and catches

    class CustomerService {
    
        public void add(Customer customer) {
            if (someCondition) {
                subscribeToNewsletter(customer);
            }
        }
    
        void subscribeToNewsletter(Customer customer) {
            // ...subscribing stuff
        }
    }
    

    Then you create a PARTIAL mock of CustomerService, giving a list of methods you want to mock.

    CustomerService customerService = PowerMock.createPartialMock(CustomerService.class, "subscribeToNewsletter");
    customerService.subscribeToNewsletter(anyObject(Customer.class));
    
    replayAll();
    
    customerService.add(createMock(Customer.class));
    

    So add() within the CustomerService mock is the REAL thing you want to test and for the method subscribeToNewsletter() you now can write an expectation as usual.

提交回复
热议问题