简体   繁体   English

如何对返回Java字符串的方法进行单元测试?

[英]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. 我正在使用Mockito进行单元测试。 I am new to both mockito and unit testing please guide. 我对mockito和单元测试都是新手,请指导。 Thanks in advance. 提前致谢。

As pointed elsewhere, using Strings for SQL statements is dangerous, regarding SQL injections. 如在其他地方指出的那样,对于SQL注入,对SQL语句使用字符串是危险的。 That being said, you simply have to call the method, and compare the result to a String you build "by hand" : 话虽如此,您只需要调用该方法,并将结果与​​您手工构建的String进行比较:

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. 在这种情况下,如果无法手动创建“ MyConfig”对象,则Mockito只会有所帮助。

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. 如果config.getABC()调用可以返回不同的值,则必须确保它始终为测试提供相同的值。 So you might have to mock your config object or put fake data into your config provider. 因此,您可能必须模拟config对象或将伪造的数据放入配置提供程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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