简体   繁体   中英

How to unit tests method returning Java string?

Hi I have plenty of methods which returns string which I need to unit tests. Now challenge for me is is how do I do code coverage? For eg 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() ;
} 

Please give your ideas how to unit tests such scenario? I am using mockito to do unit testing. I am new to both mockito and unit testing please guide. Thanks in advance.

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.

I can't see any difficulties to test a method that returns a string.

public void testSqlToDoXYZ()
{
 MyObj testTarget = new MyObj(/*Parameters if needed*/);
 Config config = new Config();
 /*Config config = new ConfigMock();*/
 String expectedResult = "SELECT BLAH BLACH WHERE ABC=123;";
 assertEquals(epxectedResult, testTarget.getSqlToDoXYZ(config));
}

The key is, that you have to know your result. If the config.getABC() call could return different values, you have to make sure it always provides the same values for your test. So you might have to mock your config object or put fake data into your config provider.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM