Software_programming_Java_UnitTest
17:57:19
Junit Rule
1. global timeout
@Rule
public MethodRule globalTimeOut = new Timeout(20)
2. ExpectedException
@Rule
public ExceptedException
3.TemporaryFolder
@Rule
public TemporaryFolder = new TemporaryFolder();
** Important
1 package framework.Junit.harmcrest_Matcher; 2 3 import org.junit.Rule; 4 import org.junit.Test; 5 import org.junit.rules.ExpectedException; 6 7 public class ExceptionWithExpectedRootCause { 8 9 @Rule 10 public ExpectedException thrown = ExpectedException.none(); 11 12 @Test 13 public void validTest() { 14 thrown.expect(new CustomExceptionMatcher().rootCauseCus_1(NullPointerException.class)); 15 throw new RuntimeException("Customer exception", new NullPointerException()); 16 } 17 18 /* public Matcher<? extends Throwable> rootCauseOf( 19 final Class<? extends Throwable> expectedCause){ 20 21 return new BaseMatcher(){ 22 @Override 23 public boolean matches(Object candidate){ 24 25 if(!(candidate instanceof Throwable)){ 26 return false; 27 } 28 29 Throwable cause = ((Throwable) candidate).getCause(); 30 31 if(cause == null){ 32 return false; 33 } 34 35 return expectedCause.isAssignableFrom(cause.getClass()); 36 } 37 38 @Override 39 public void describeTo(Description description){ 40 description.appendText("Throwable with cause of type "); 41 description.appendText(expectedCause.getSimpleName()); 42 } 43 };*/ 44 45 }
Temporary File Folder
1 package framework.Junit.harmcrest_Matcher; 2 3 import org.junit.Rule; 4 import org.junit.Test; 5 import org.junit.rules.TemporaryFolder; 6 7 import java.io.File; 8 import java.io.IOException; 9 10 import static junit.framework.TestCase.assertTrue; 11 12 public class TempFileSystemTest { 13 14 @Rule 15 public TemporaryFolder folder = new TemporaryFolder(); 16 17 @Test 18 public void thisTempFileIsSquashedAfterTheTest() throws Exception { 19 File file = folder.newFile("myTmpFile.json"); 20 assertTrue(file.exists()); 21 } 22 23 @Test 24 public void allJunkWillBeGoneAfterTheTestHasRun() throws IOException { 25 File tmpDir = folder.newFolder("MyTmpDir"); 26 assertTrue(tmpDir.exists()); 27 } 28 }