Search code examples
javaunit-testingmockitojunit4

How to unit test method returning Java string?


I have plenty of methods which returns string which I need to unit test. Now challenge for me is is how do I do code coverage? For example, my method looks like the following:

Public String getSqlToDoXYZ(Myconfig config) {
StringBuilder sb = new StringBuilder() ;
sb.append(  "SELECT BLAH BLAH");
sb.append("WHERE ABC="+config.getABC());
return sb.toString() ;
} 

How can I unit test such scenario? I am using Mockito to do unit testing. I am new to both Mockito and unit testing.


Solution

  • As pointed elsewhere, using Strings for SQL statements is dangerous, regarding SQL injections. That being said, you simply have to call the method, and compare the result to a String you build "by hand" :

    public void testBuildSqlToDoXYZ() throws Exception {
    
       WhateverYourObjectIs yourObject = new WhateverYourObjectIs();
       MyConfig myConfig = new MyConfig();
       myConfig.setABC("foo");
    
       String sql = yourObject.getSqlToDoXYZ(myConfig);
       assertEquals("SELECT BLAH BLAH WHERE ABC='foo'", sql);
    
    }
    

    Mockito would only be helpfull in this case if is impossible for you to create a "MyConfig" object by hand.

    There might be something else in your code that makes that difficult, but you haven't really provided us enough info.