Reputation: 165
I am trying to run create some tests for the program I have. I am still new to Java and programming as a whole so I am unsure what to do. I have a .csv file lets just call it testdata.csv and I want to look for certain words within that test file for a test. So for example a test that can display multiple strings from within that file and say they are in there.
I have tried using assert.that but it didn't work for me I probably did it wrong. Was just searching online and trying to piece things together. The code I had included was the last attempt I had done and I know it isn't right...
@org.junit.Test
public void testAssets (){
String fileName;
fileName = "testdata.csv";
Assert.that(fileName, hasItems);
For the test to fail if it doesn't have the string "UDP,TCP,ICMP"
Upvotes: 0
Views: 103
Reputation: 186
Unit testing is about testing your code in isolation to ensure that one piece, or unit, functions as intended. In your case above, you want to test whether the logic which operates on a String
read in from a file (or anywhere else for that matter) will detect what it is meant to detect.
Let's say you have a method:
public boolean isAMatch(String input)
{
return (input.contains("UDP") || input.contains("TCP") || input.contains("ICMP"))
}
Your test for this method, or unit if code, should look something like:
private void testIsAMatch()
{
Assert.assertTrue(isAMatch("This String contains UDP."));
Assert.assertTrue(isAMatch("This String contains TCP."));
Assert.assertTrue(isAMatch("This String contains ICMP."));
Assert.assertFalse(isAMatch("This String does not match."));
}
The idea behind unit testing is that your testing your code to be working independent of outside sources (such as a file, database connection, website, etc.). What if the file gets edited or deleted? How will you know where your failure is? Unit testing is designed to tell you quickly whether a code change caused your logic to break. In this way, you can parse your .csv file into one big string, or smaller strings, or however, and pass that input to your isAMatch()
method. If it returns false but your unit tests pass, and assuming you are reading the file properly, you can be comfortable that the file does not contain the match you are looking for.
Upvotes: 1