juan_gandhi: (Default)
[personal profile] juan_gandhi
Being tired of having to repeat all the small cheap unittesting gadgets here and there, introduced OurTestCase extends TestCase where I stuff all kinds of stuff, like, e.g., this:

    protected void assertJsonEquals(String message, String x, String y) 
    {
        JSONObject jsonX = jsonFor(message, x);
        JSONObject jsonY = jsonFor(message, y);
        assertEquals(message, jsonX, jsonY);
    }

    private JSONObject jsonFor(String message, String x)
            throws AssertionFailedError
    {
        try
        {
            return new JSONObject(x);
        } catch (JSONException e)
        {
           throw new AssertionFailedError(message + ": bad json: " + e + "\n" + x);
        }
    }
    
    protected void assertEquals(JSONObject x, JSONObject y)
    {
        assertEquals("failed", x, y);
    }

    protected void assertEquals(String message, JSONObject x, JSONObject y) 
    {
        assertNotNull(message, x);
        assertNotNull(message, y);
        if (x.equals(y)) return;
        for (Enumeration e = x.keys(); e.hasMoreElements();)
        {
            String key = e.nextElement().toString();
            assertTrue(message + ": key " + key + " missing in " + y, y.has(key));
        }

        for (Enumeration e = y.keys(); e.hasMoreElements();)
        {
            String key = e.nextElement().toString();
            assertTrue(message + ": key " + key + " missing in " + x, x.has(key));
        }

        for (Enumeration e = x.keys(); e.hasMoreElements();)
        {
            String key = e.nextElement().toString();
            try
            {
                Object itemX = x.get(key);
                Object itemY = y.get(key);
                if (itemX != itemY) {
                    String newMessage = message + ".key=" + key;
                    if (itemX instanceof JSONObject && itemY instanceof JSONObject) {
                        assertEquals(newMessage, (JSONObject) itemX, (JSONObject) itemY);
                    } else {
                        assertEquals(newMessage, x.get(key), y.get(key));
                    }
                }
            } catch (JSONException ex)
            {
                fail(message + ": key=" + key + ": " + ex.getMessage());
            }
        }

    }
This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

May 2025

S M T W T F S
    1 2 3
456 7 8 9 10
11 121314151617
181920 21 222324
25262728293031

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated May. 24th, 2025 01:11 am
Powered by Dreamwidth Studios