2012-10-20 12 views
7

मैं junit ExpectedExceptions' javadoc ब्राउज़ कर रहा था और मुझे समझ में नहीं आया कि उनके उदाहरण में startsWith कहां से आया है (कोड में यहां चिह्नित)। मैंने CoreMatcher utility class की जांच की लेकिन कोई स्थिर startsWith विधि नहीं मिली।जुनीट मचर # की शुरुआत कहां से शुरू होती है?

वह विधि कहां स्थित है?

(मैं स्पष्ट रूप से इसे अपने आप को लिख सकते हैं लेकिन उस समय नहीं है)

public static class HasExpectedException { 
    @Rule 
    public ExpectedException thrown = ExpectedException.none(); 

    @Test 
    public void throwsNullPointerExceptionWithMessage() { 
     thrown.expect(NullPointerException.class); 
     thrown.expectMessage("happened?"); 
     thrown.expectMessage(startsWith("What")); //HERE 
     throw new NullPointerException("What happened?"); 
    } 
} 

उत्तर

7

सबसे अधिक संभावना इस Hamcrest Matchers class से startsWith तरीका है।

3

ExpectedException पर देखकर, हम देख सकते हैं कि दो अपेक्षाएं हैं, मैसेज विधियों को परिभाषित किया गया है, एक स्ट्रिंग और एक मैचर, जो वास्तव में org.hamcrest.Matcher है।

/** 
* Adds to the list of requirements for any thrown exception that it should 
* <em>contain</em> string {@code substring} 
*/ 
public void expectMessage(String substring) { 
    expectMessage(containsString(substring)); 
} 

/** 
* Adds {@code matcher} to the list of requirements for the message returned 
* from any thrown exception. 
*/ 
public void expectMessage(Matcher<String> matcher) { 
    expect(hasMessage(matcher)); 
} 
5
import static org.hamcrest.core.StringStartsWith.startsWith; 

दोनों

assertThat(msg, startsWith ("what")); 

और

ExpectedException.none().expectMessage(startsWith("What")); //HERE 
सक्षम बनाता है