assertEquals("March", monthMap.get(3)); // JUnit assertThat(monthMap).containsEntry(3, "March"); // Truth
ImmutableSet<String> colors = ImmutableSet.of("red", "green", "blue", "yellow"); assertTrue(colors.contains("orange")); // JUnit assertThat(colors).contains("orange"); // Truth
npm install -g protractor
webdriver-manager update & webdriver-manager start
// It is a good idea to use page objects to modularize your testing logic var angularHomepage = { nameInput : element(by.model('yourName')), greeting : element(by.binding('yourName')), get : function() { browser.get('index.html'); }, setName : function(name) { this.nameInput.sendKeys(name); } }; // Here we are using the Jasmine test framework // See http://jasmine.github.io/2.0/introduction.html for more details describe('angularjs homepage', function() { it('should greet the named user', function(){ angularHomepage.get(); angularHomepage.setName('Julie'); expect(angularHomepage.greeting.getText()). toEqual('Hello Julie!'); }); });
exports.config = { seleniumAddress: 'http://localhost:4444/wd/hub', specs: ['testFolder/*'], multiCapabilities: [{ 'browserName': 'chrome', // browser-specific tests specs: 'chromeTests/*' }, { 'browserName': 'firefox', // run tests in parallel shardTestFiles: true }], baseUrl: 'http://www.angularjs.org', };
protractor conf.js
1 test, 1 assertions, 0 failures
@Test public void isUserLockedOut_invalidLogin() { authenticator.authenticate(username, invalidPassword); assertFalse(authenticator.isUserLockedOut(username)); authenticator.authenticate(username, invalidPassword); assertFalse(authenticator.isUserLockedOut(username)); authenticator.authenticate(username, invalidPassword); assertTrue(authenticator.isUserLockedOut(username)); }
bool WaitForCallToComeUp(content::WebContents* tab_contents) { // Apprtc will set remoteVideo.style.opacity to 1 when the call comes up. std::string javascript = "window.domAutomationController.send(remoteVideo.style.opacity)"; return test::PollingWaitUntil(javascript, "1", tab_contents); }
bool DetectRemoteVideoPlaying(content::WebContents* tab_contents) { if (!EvalInJavascriptFile(tab_contents, GetSourceDir().Append( FILE_PATH_LITERAL( "chrome/test/data/webrtc/test_functions.js")))) return false; if (!EvalInJavascriptFile(tab_contents, GetSourceDir().Append( FILE_PATH_LITERAL( "chrome/test/data/webrtc/video_detector.js")))) return false; // The remote video tag is called remoteVideo in the AppRTC code. StartDetectingVideo(tab_contents, "remoteVideo"); WaitForVideoToPlay(tab_contents); return true; }
if (!HasWebcamOnSystem()) return;
google_appengine/dev_appserver.py apprtc_code/
bool LaunchApprtcInstanceOnLocalhost() // ... Figure out locations of SDK and apprtc code ... CommandLine command_line(CommandLine::NO_PROGRAM); EXPECT_TRUE(GetPythonCommand(&command_line)); command_line.AppendArgPath(appengine_dev_appserver); command_line.AppendArgPath(apprtc_dir); command_line.AppendArg("--port=9999"); command_line.AppendArg("--admin_port=9998"); command_line.AppendArg("--skip_sdk_update_check"); VLOG(1) << "Running " << command_line.GetCommandLineString(); return base::LaunchProcess(command_line, base::LaunchOptions(), &dev_appserver_); }
bool LocalApprtcInstanceIsUp() { // Load the admin page and see if we manage to load it right. ui_test_utils::NavigateToURL(browser(), GURL("localhost:9998")); content::WebContents* tab_contents = browser()->tab_strip_model()->GetActiveWebContents(); std::string javascript = "window.domAutomationController.send(document.title)"; std::string result; if (!content::ExecuteScriptAndExtractString(tab_contents, javascript, &result)) return false; return result == kTitlePageOfAppEngineAdminPage; }
while (!LocalApprtcInstanceIsUp()) VLOG(1) << "Waiting for AppRTC to come up...";
from mozprofile import profile from mozrunner import runner WEBRTC_PREFERENCES = { 'media.navigator.permission.disabled': True, } def main(): # Set up flags, handle SIGTERM, etc # ... firefox_profile = profile.FirefoxProfile(preferences=WEBRTC_PREFERENCES) firefox_runner = runner.FirefoxRunner( profile=firefox_profile, binary=options.binary, cmdargs=[options.webpage]) firefox_runner.start()
GURL room_url = GURL(base::StringPrintf("http://localhost:9999?r=room_%d", base::RandInt(0, 65536))); content::WebContents* chrome_tab = OpenPageAndAcceptUserMedia(room_url); ASSERT_TRUE(LaunchFirefoxWithUrl(room_url));
run_firefox_webrtc.py --binary /path/to/firefox --webpage http://localhost::9999?r=my_room
<div class="button">Save</div>
<div class="button">Edit</div>
div.button
//div[@class='button' and text()='Save']
contact-form.save-button contact-form.edit-button
@Override protected void onEnsureDebugId(String baseId) { super.onEnsureDebugId(baseId); saveButton.ensureDebugId(baseId + ".save-button"); editButton.ensureDebugId(baseId + ".edit-button"); }
<tr id="feedback-{{$index}}" class="feedback" ng-repeat="feedback in ctrl.feedbacks" >
@UiField FlexTable table; UIObject.ensureDebugId(table.getCellFormatter().getElement(rowIndex, columnIndex), baseID + colIndex + "-" + rowIndex);
@Test public void shouldNavigateToPhotosPage() { String baseUrl = "http://plus.google.com/"; Navigator nav = new Navigator(baseUrl); nav.goToPhotosPage(); assertEquals(baseUrl + "/u/0/photos", nav.getCurrentUrl()); }
@Test public void shouldNavigateToPhotosPage() { Navigator nav = new Navigator("http://plus.google.com/"); nav.goToPhotosPage(); assertEquals("http://plus.google.com//u/0/photos", nav.getCurrentUrl()); // Oops! }
@Test public void testProcessTransaction() { User user = newUserWithBalance(LOW_BALANCE_THRESHOLD.plus(dollars(2)); transactionProcessor.processTransaction( user, new Transaction("Pile of Beanie Babies", dollars(3))); assertContains("You bought a Pile of Beanie Babies", ui.getText()); assertEquals(1, user.getEmails().size()); assertEquals("Your balance is low", user.getEmails().get(0).getSubject()); }
@Test public void testProcessTransaction_displaysNotification() { transactionProcessor.processTransaction( new User(), new Transaction("Pile of Beanie Babies")); assertContains("You bought a Pile of Beanie Babies", ui.getText()); } @Test public void testProcessTransaction_sendsEmailWhenBalanceIsLow() { User user = newUserWithBalance(LOW_BALANCE_THRESHOLD.plus(dollars(2)); transactionProcessor.processTransaction( user, new Transaction(dollars(3))); assertEquals(1, user.getEmails().size()); assertEquals("Your balance is low", user.getEmails().get(0).getSubject()); }
class LinkGeneratorTest(googletest.TestCase): def setUp(self): self.generator = link_generator.LinkGenerator() def testGetLinkFromIDs(self): expected = ('https://frontend.google.com/advancedSearchResults?' 's.op=ALL&s.r0.field=ID&s.r0.val=1288585+1310696+1346270+') actual = self.generator.GetLinkFromIDs(set((1346270, 1310696, 1288585))) self.assertEqual(expected, actual)
import urllib class LinkGenerator(object): _URL = ( 'https://frontend.google.com/advancedSearchResults?' 's.op=ALL&s.r0.field=ID&s.r0.val=') def GetLinkFromIDs(self, ids): result = [] for id in sorted(ids): result.append('%s ' % id) return self._URL + urllib.quote_plus(''.join(result))
@Test public void shouldPerformAddition() { Calculator calculator = new Calculator(new RoundingStrategy(), "unused", ENABLE_COSIN_FEATURE, 0.01, calculusEngine, false); int result = calculator.doComputation(makeTestComputation()); assertEquals(5, result); // Where did this number come from? }
@Test public void shouldPerformAddition() { Calculator calculator = newCalculator(); int result = calculator.doComputation(makeAdditionComputation(2, 3)); assertEquals(5, result); }
interface Service { Data get(); }
when(service.get()).thenReturn(cannedData);
interface Service { void get(Callback callback); }
doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { Callback callback = (Callback) invocation.getArguments()[0]; callback.onSuccess(cannedData); return null; } }).when(service).get(any(Callback.class));
interface Translator { String translate(String msg); }
when(translator.translate(any(String.class))).thenAnswer(reverseMsg()) ... // extracted a method to put a descriptive name private static Answer<String> reverseMsg() { return new Answer<String>() { public String answer(InvocationOnMock invocation) { return reverseString((String) invocation.getArguments()[0])); } } }