In this solution, the production class actually loads a file from the disk
The Unit Test
Code Block |
---|
|
using NUnit.Framework;
using file_loader_service;
namespace file_loader_tests
{
public class FileLoaderTests
{
[Test]
package com.celestial.mockito.filetodb;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
*
* @author selvy
*/
public class LiveFileLoaderTest
{
// The inital design is described in this test
/*
The weakness should be obvious? The file to be loaded and it's location
I use a shared network drive to run this code from different machines, normally
dev-ing from a PC. When I ran the code on the laptop from a cafe it
immediately failed because the C: on the laptop was completely different
to the PC, so the original file C:/tmp/KeyboardHandler.txt did not exist
THIS IS A GREAT EXAMPLE OF WHY THE UNIT TEST AND CUT SHOULD NOT BE STRONGLY
LINKED TO ANY IO - NETWORK, DB, AND FILE SYSTEM
*/
@Test
public void load_all_of_file_using_inbuilt_Files_type()
{
// arrange
String string fileToLoad = "c:/tmp/KeyboardHandler.java.txt";
FileLoader cut = new FileLoader(fileToLoad);
int expectedBytesRead = 1383;
// act
int bytesRead = cut.LoadFileloadFile(fileToLoad);
// assert
Assert.AreEqualassertEquals(expectedBytesRead, bytesRead);
}
}
} |
The CUT FileLoader
Code Block |
---|
|
using Systempackage com.celestial.mockito.filetodb;
using
import Systemjava.Collectionsio.GenericIOException;
using System.IOimport java.nio.charset.StandardCharsets;
namespace file_loader_service
{
public class FileLoader
{
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
/**
*
* @author selvy
*/
public class FileLoader
{
private string fileData;class IntWrapper
{
IEnumerable<string> lines = newpublic List<string>(); int value;
}
public FileLoader()
String fileToLoad;
{List<String> lines = Collections.emptyList();
public }FileLoader(String fileToLoad)
{
public int LoadFile(string fname) this.fileToLoad = fileToLoad;
}
{ int loadFile(String fname)
{
try try
{
lines = File.ReadLinesFiles.readAllLines(Paths.get(fname), StandardCharsets.UTF_8);
}
catch (IOException e) { }
return CalculateFileSizecalculateFileSize();
}
private int CalculateFileSizecalculateFileSize()
{
IntWrapper int result = new 0IntWrapper();
foreach (string line in lines)
lines.forEach(line -> {
result.value += line.Lengthlength();
});
return result;
}
.value;
}
} |