If you want to switch between different implementations in different situations, strategy pattern is an ideal solutions. Recently I used this pattern for process the output in android UI tests. So depending on the situation the out put was redirected to either Logcat or a text file. This is how it was implemented.
This is the service class.
For any query, feel free to contact me via my linkedin profile.
This is the service class.
public class ReportService { publicThis is the interface for the strategy classes.void generateReport(T data, ReportStrategy strategy ){ strategy.generateReport(data); } }
public interface ReportStrategy{ public void generateReport(T data); }
Class for the Logcat output strategy.Here the TestCasePoint class contains the test results.
public class LogCatReportStrategy implements ReportStrategy<TestCasePoint>Class for the text file output strategy.{ public static final String LOGNAME = "Logindicator"; @Override public void generateReport(TestCasePoint data) { Log.d(LOGNAME,"*****************************"); String testCaseID = "Testcase ID = "+data.getTestCaseID(); Log.d(LOGNAME,testCaseID); for (ControllerPoint point : data.getControllPoints()) { String level = "********"; String controllerID = level+"Controller ID = "+point.getId(); String testStatus = level+point.getTestResult(); Log.d(LOGNAME,controllerID); Log.d(LOGNAME,"Result = "+testStatus); } Log.d(LOGNAME,"Test case result "+data.getResult().toString()); Log.d(LOGNAME,"*****************************"); } }
public class TextFileReportStratergy implements ReportStrategy<TestCasePoint>This is how log cat strategy can be used.{ @Override public void generateReport(TestCasePoint data) { File file = null; try { file = new File(Environment.getDataDirectory(), "Report.txt"); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(Environment.getDataDirectory(),"Report.txt"))); writer.write("*****************************\n"); writer.write("Testcase ID = " + data.getTestCaseID()+"\n"); for (ControllerPoint point : data.getControllPoints()){ String level = "********"; String controllerID = level+"Controller ID = "+point.getId()+"\n"; String testStatus = point.getTestResult().toString(); writer.write(controllerID); writer.write(level+"Result = " + testStatus+"\n"); } writer.write( "Test case result " + data.getResult().toString()+"\n"); writer.write("*****************************\n"); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
ReportService service = new ReportService(); ReportStrategyThis is how text file strategy can be used.strategy = new LogCatReportStrategy(); service.generateReport(testResult, strategy);
ReportStrategy strategyTextFile = new TextFileReportStratergy(); service.generateReport(testResult, strategyTextFile);
For any query, feel free to contact me via my linkedin profile.
No comments:
Post a Comment