Java – unit testing of methods that use mockito to call multiple other methods

Maybe I didn't do it at all in the search, but I can't find any documentation or discussion about how to write unit tests for Java classes / methods, which call other non private methods It seems that if spies have to be used to test a method that needs to simulate internal method calls, mockito will think that there may be a problem with the design (not a real OO) I'm not sure it's forever But the use of spies seems to be the only way to achieve this goal For example, why can't you have a "wrapper" style method that relies on other methods of the original function, but also provides functions, error handling, logging or different branches that depend on the results of other methods?

So my question is twofold:

>Do poorly designed and implemented code have internal methods to call other methods? > If mockito is chosen as their simulation framework, what are the best practices and / or methods for writing unit tests for this approach (assuming it is a good idea in itself)?

This may be a difficult request, but I prefer those who decide to answer not only to republish the wording of mockito and / or their position on espionage, because I am aware of this method and ideology In addition, I have also used powermockito For me, the problem is that mockito developed this framework, in which additional solutions must be created to support this requirement So I think the question I want to answer is, if the spy is "bad" and powermockito is not available, how to unit test a method that calls other non private methods?

Solution

Not really But what I want to say is that in this case, methods that call other methods should be tested, just like other methods that have not been tested separately That is, it protects you from situations where public methods stop calling other methods without noticing

Yes, it (sometimes) produces a lot of test code I believe that's the point: the pain of writing tests is a good clue, and you may want to consider extracting these sub methods into a separate class

If I can stand those tests, I don't think the sub methods have been extracted yet

I would do something like that:

public class Blah {
    public int publicMethod() {
        return innerMethod();
    }

    int innerMethod() {
        return 0;
    }
}


public class BlahTest {
    @Test
    public void blah() throws Exception {
        Blah spy = spy(new Blah());
        doReturn(1).when(spy).innerMethod();

        assertThat(spy.publicMethod()).isEqualTo(1);
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>