Refactoring for Tests - Handout

  • 78 views
Uploaded on

When working with legacy code, subsequent covering with unit tests is not an easy task. Quite often one is faced with the dilemma of refactoring - you need tests for safely refactorings, but the code …

When working with legacy code, subsequent covering with unit tests is not an easy task. Quite often one is faced with the dilemma of refactoring - you need tests for safely refactorings, but the code needs to be refactored first in order to write any tests.
 
Bringing existing code in better shape is essential when existing code must be covered with unit tests. In this presentation we focus on refactorings that are targeted for covering legacy code with unit tests, after it has been written without tesing in mind.

This is the handout for the presentation. See also:
- Slides: http://www.slideshare.net/rfilipov/refactoring-for-tests-0lides
- Sources: https://github.com/rusio/refactoring-for-tests

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
78
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
2
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. public class Original { // Coupling: Static Dependencies 1 public void usage() { BookingService bookingService = new BookingService(); bookingService.bookConference("Big Trouble in Little China"); } } public class BookingService { public BookingResult bookConference(String topic) { ConferencingServer conferencingServer = new ConferencingServer(); MeetingCalendar meetingCalendar = MeetingCalendar.getInstance(); Date startDate = meetingCalendar.nextPossibleDate(); try { return conferencingServer.bookConference(topic, startDate); } catch (BookingException e) { return BookingResult.forFailure(e); } } } class ConferencingServer { public BookingResult bookConference(String topic, Date startDate) throws BookingException { // NOTE: real implementation would connect to // the conferencing server and book the conference return BookingResult.forSuccess("0721/480848-000", startDate); } } class MeetingCalendar { private static final MeetingCalendar instance = new MeetingCalendar(); private MeetingCalendar() { // enforce Singleton } public static MeetingCalendar getInstance() {
  • 2. return instance; } public Date nextPossibleDate() { // NOTE: real implementation would look up some // calendar database and calculate the date return new Date(); } } public final class BookingResult { private final BookingException errorCause; private final String phoneNumber; private final Date startDate; private BookingResult(BookingException errorCause, String phoneNumber, Date startDate) { this.errorCause = errorCause; this.phoneNumber = phoneNumber; this.startDate = startDate; } public static BookingResult forSuccess(String phoneNumber, Date startDate) { return new BookingResult(null, phoneNumber, startDate); } public static BookingResult forFailure(BookingException error) { return new BookingResult(error, null, null); } public boolean isSuccess() { return errorCause == null; } public String getPhoneNumber() { return phoneNumber; } public Date getStartDate() { return startDate; } public BookingException getErrorCause() { return errorCause; } }
  • 3. public class Original { // Coupling: Static Dependencies 2 public void usage() throws BookingException { // NOTE: the real implementation would create // these objects at a central place. BigFatContext bigFatContext = new BigFatContext(); BookingService bookingService = new BookingService(bigFatContext); bookingService.bookConference("Big Trouble in Little China"); } } /** * NOTE: imagine it is difficult to instantiate this * class and its collaborators in a test harness. */ public final class BigFatContext extends FrameworkClass { private final Map<String, Object> services = new HashMap<String, Object>(); public BigFatContext() { // NOTE: the map contains real objects, which are created here // => how to replace these two with mock objects in a test? services.put("conferencingServer", new ConferencingServerImpl()); services.put("meetingCalendar", new MeetingCalendarImpl()); } public ConferencingServer getConferencingServer() { return (ConferencingServer) services.get("conferencingServer"); } public MeetingCalendar getMeetingCalendar() { return (MeetingCalendar) services.get("meetingCalendar"); } } public class BookingService { private final BigFatContext bigFatContext; public BookingService(BigFatContext bigFatContext) { this.bigFatContext = bigFatContext; }
  • 4. public BookingResult bookConference(String topic) throws BookingException { MeetingCalendar meetingCalendar = bigFatContext.getMeetingCalendar(); Date startDate = meetingCalendar.nextPossibleDate(); try { ConferencingServer conferencingServer = bigFatContext.getConferencingServer(); return conferencingServer.bookConference(topic, startDate); } catch (BookingException e) { return BookingResult.forFailure(e); } } }
  • 5. public class Original { // Coupling: Dynamic Dependencies public void usage() throws BookingException { // sample setup ConferencingServer conferencingServer = new ConferencingServerImpl(); MeetingCalendar meetingCalendar = new MeetingCalendarImpl(); BookingService bookingService = new BookingService(conferencingServer, meetingCalendar); NotificationService notificationService = new NotificationService(); // sample usage BookingResult bookingResult = bookingService.bookConference("Big Trouble in Little China"); if (bookingResult.isSuccess()) { List<String> participantUris = asList("sip:Jack.Burton@trucker.com", "mailto:Egg.Shen@magician.com"); notificationService.notifyParticipants(participantUris, bookingResult.getStartDate()); } } } public class NotificationService { public NotificationResult notifyParticipants(List<String> participantUris, Date startDate) { // prepare the info text about the conference String notificationMessage = buildNotificationMessage(startDate); // notify the participants NotificationResult result = new NotificationResult(); for (String participantUri : participantUris) { try { notifyParticipant(participantUri, notificationMessage); } catch (NotificationException e) { result.addError(participantUri, e); } } return result; } private String buildNotificationMessage(Date startDate) {
  • 6. String text = "Time for Kung-Fu! We will call you at %s."; return String.format(text, startDate); } private void notifyParticipant(String participantUri, String notificationMessage) throws NotificationException { if (participantUri.startsWith("sip:")) { InstantMessenger instantMessenger = new InstantMessenger(); instantMessenger.sendMessage(participantUri, notificationMessage); } else if (participantUri.startsWith("mailto:")) { EmailSender emailSender = new EmailSender(); emailSender.sendEmail(participantUri, notificationMessage); } } }
  • 7. public class Original { // Distraction public void usage() throws Exception { FtpClient ftpClient = new FtpClient("ftp://my.server.de"); List<String> fileNames = ftpClient.listFiles("*.rec"); for (String fileName : fileNames) { File localFile = ftpClient.downloadFile(fileName, "Bx3A2v34fhq4367"); } } } public class FtpClient { private static final int RECONNECT_RETRIES = 3; private final String serverUrl; private final Cache<String, List<String>> cachedLists; public FtpClient(String serverUrl) { this.serverUrl = serverUrl; this.cachedLists = CacheBuilder.newBuilder() .expireAfterAccess(1, TimeUnit.MINUTES) .build(); } public List<String> listFiles(String pattern) throws IOException { try { return cachedLists.get(pattern, new Callable<List<String>>() { @Override public List<String> call() throws Exception { establishConnection(RECONNECT_RETRIES); // NOTE: imagine this lists the remote FTP files // according to the given filename pattern List<String> remoteFiles = asList("conference-0.rec", "conference-1.rec"); return remoteFiles; } }); } catch (ExecutionException e) { throw new IOException(e); } }
  • 8. public File downloadFile(String fileName, String checksum) throws IOException { establishConnection(RECONNECT_RETRIES); // NOTE: imagine this downloads the file in /tmp File localFile = new File("/tmp", fileName); checkChecksum(localFile, checksum); return localFile; } private void checkChecksum(File localFile, String checksum) throws IOException { byte[] fileBytes = Files.readAllBytes(localFile.toPath()); HashFunction hashFunction = Hashing.md5(); HashCode expectedHashCode = hashFunction.hashString(checksum); HashCode actualHashCode = hashFunction.hashBytes(fileBytes); if (!actualHashCode.equals(expectedHashCode)) { throw new IOException("Bad checksum after download!"); } } private void establishConnection(int retriesLeft) throws IOException { try { // NOTE: simulate some connection problems System.out.println("Connecting to " + serverUrl); if (Math.random() < 0.2) { throw new IOException("Connection refused!"); } } catch (IOException e) { if (retriesLeft > 0) { establishConnection(retriesLeft - 1); } else { throw new IOException("Failed after " + RECONNECT_RETRIES + " retries", e); } } } }