PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, May 18, 2022

[FIXED] How do you not do partial mocking in this scenario?

 May 18, 2022     java, mocking, partial, unit-testing     No comments   

Issue

Let's say I wrote a pretty simple class called ValueFinder that looks like this:

public class ValueFinder {

    public String findValue(Object obj) {
        String value = null;
        value = findValueFirstWay(obj);
        if (value == null) {
            value = findValueSecondWay(obj);
        }
        return value;
    }

    protected String findValueFirstWay(Object obj) {
        ....
    }

    protected String findValueSecondWay(Object obj) {
        ....
    }
}

Now I want to test that findValueFirstWay is really the first method attempted when calling findValue. This is a very simple class, the "algorithms" of the ways are very simple. Without doing a partial mock where findValueFirstWay and findValueSecondWay are mocked and findValue is left alone, how do I test that?

I assume I'm supposed to refactor the class so that findValueFirstWay and findValueSecondWay are in a separate class or classes? It just seems like unnecessary work for something so simple.


Solution

You could avoid mocking entirely and test it by the visible effect with real objects.

Or you could mock the objects being passed in as values, and expect whatever calls that the findValueFirstWay(Object obj) makes to the obj that cause it to return a null, etc.

However, even though it seems simple, my first impulse would still be to extract the problem methods to a separate class or two, so that the interaction can be more naturally tested with mocks.



Answered By - Don Roby
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing