method2testcases
stringlengths
118
3.08k
### Question: Volume { public Volume withPath(String path) { this.path = path; return this; } String getPath(); String getSize(); Boolean isPersist(); Volume withPath(String path); Volume withSize(String size); Volume withPersist(Boolean persist); }### Answer: @Test public void testWithPath() { final Volume volume = new Volume(); volume.withPath("/home/shared"); assertEquals("/home/shared", volume.getPath()); }
### Question: Volume { public Volume withSize(String size) { this.size = size; return this; } String getPath(); String getSize(); Boolean isPersist(); Volume withPath(String path); Volume withSize(String size); Volume withPersist(Boolean persist); }### Answer: @Test public void testWithSize() { final Volume volume = new Volume(); volume.withSize("10G"); assertEquals("10G", volume.getSize()); }
### Question: Volume { public Volume withPersist(Boolean persist) { this.persist = persist; return this; } String getPath(); String getSize(); Boolean isPersist(); Volume withPath(String path); Volume withSize(String size); Volume withPersist(Boolean persist); }### Answer: @Test public void testWithPersist() { final Volume volume = new Volume(); volume.withPersist(true); assertEquals(Boolean.TRUE, volume.isPersist()); }
### Question: DeploymentSettings extends BaseSettings { public void setCpu(String cpu) { this.cpu = cpu; } String getCpu(); String getMemoryInGB(); String getInstanceCount(); String getDeploymentName(); void setCpu(String cpu); void setMemoryInGB(String memoryInGB); void setInstanceCount(String instanceCount); void setJvmOptions(String jvmOptions); void setDeploymentName(String deploymentName); String getJvmOptions(); String getRuntimeVersion(); void setRuntimeVersion(String runtimeVersion); }### Answer: @Test public void testSetCpu() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setCpu("1"); assertEquals("1", deploy.getCpu()); }
### Question: DeploymentSettings extends BaseSettings { public void setMemoryInGB(String memoryInGB) { this.memoryInGB = memoryInGB; } String getCpu(); String getMemoryInGB(); String getInstanceCount(); String getDeploymentName(); void setCpu(String cpu); void setMemoryInGB(String memoryInGB); void setInstanceCount(String instanceCount); void setJvmOptions(String jvmOptions); void setDeploymentName(String deploymentName); String getJvmOptions(); String getRuntimeVersion(); void setRuntimeVersion(String runtimeVersion); }### Answer: @Test public void testSetMemoryInGB() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setMemoryInGB("2"); assertEquals("2", deploy.getMemoryInGB()); }
### Question: DeploymentSettings extends BaseSettings { public void setInstanceCount(String instanceCount) { this.instanceCount = instanceCount; } String getCpu(); String getMemoryInGB(); String getInstanceCount(); String getDeploymentName(); void setCpu(String cpu); void setMemoryInGB(String memoryInGB); void setInstanceCount(String instanceCount); void setJvmOptions(String jvmOptions); void setDeploymentName(String deploymentName); String getJvmOptions(); String getRuntimeVersion(); void setRuntimeVersion(String runtimeVersion); }### Answer: @Test public void testSetInstanceCount() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setInstanceCount("3"); assertEquals("3", deploy.getInstanceCount()); }
### Question: DeploymentSettings extends BaseSettings { public void setDeploymentName(String deploymentName) { this.deploymentName = deploymentName; } String getCpu(); String getMemoryInGB(); String getInstanceCount(); String getDeploymentName(); void setCpu(String cpu); void setMemoryInGB(String memoryInGB); void setInstanceCount(String instanceCount); void setJvmOptions(String jvmOptions); void setDeploymentName(String deploymentName); String getJvmOptions(); String getRuntimeVersion(); void setRuntimeVersion(String runtimeVersion); }### Answer: @Test public void testSetDeploymentName() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setDeploymentName("deploymentName1"); assertEquals("deploymentName1", deploy.getDeploymentName()); }
### Question: DeploymentSettings extends BaseSettings { public void setJvmOptions(String jvmOptions) { this.jvmOptions = jvmOptions; } String getCpu(); String getMemoryInGB(); String getInstanceCount(); String getDeploymentName(); void setCpu(String cpu); void setMemoryInGB(String memoryInGB); void setInstanceCount(String instanceCount); void setJvmOptions(String jvmOptions); void setDeploymentName(String deploymentName); String getJvmOptions(); String getRuntimeVersion(); void setRuntimeVersion(String runtimeVersion); }### Answer: @Test public void testSetJvmOptions() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setJvmOptions("jvmOptions1"); assertEquals("jvmOptions1", deploy.getJvmOptions()); }
### Question: DeploymentSettings extends BaseSettings { public void setRuntimeVersion(String runtimeVersion) { this.runtimeVersion = runtimeVersion; } String getCpu(); String getMemoryInGB(); String getInstanceCount(); String getDeploymentName(); void setCpu(String cpu); void setMemoryInGB(String memoryInGB); void setInstanceCount(String instanceCount); void setJvmOptions(String jvmOptions); void setDeploymentName(String deploymentName); String getJvmOptions(); String getRuntimeVersion(); void setRuntimeVersion(String runtimeVersion); }### Answer: @Test public void testSetRuntimeVersion() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setRuntimeVersion("8"); assertEquals("8", deploy.getRuntimeVersion()); }
### Question: SpringConfiguration { public SpringConfiguration withSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } Boolean isPublic(); String getSubscriptionId(); String getResourceGroup(); String getClusterName(); String getAppName(); String getRuntimeVersion(); String getActiveDeploymentName(); Deployment getDeployment(); SpringConfiguration withPublic(Boolean isPublic); SpringConfiguration withSubscriptionId(String subscriptionId); SpringConfiguration withResourceGroup(String resourceGroup); SpringConfiguration withClusterName(String clusterName); SpringConfiguration withAppName(String appName); SpringConfiguration withRuntimeVersion(String runtimeVersion); SpringConfiguration withActiveDeploymentName(String deploymentName); SpringConfiguration withDeployment(Deployment deployment); }### Answer: @Test public void testWithSubscriptionId() { final SpringConfiguration config = new SpringConfiguration(); config.withSubscriptionId("subscriptionId1"); assertEquals("subscriptionId1", config.getSubscriptionId()); }
### Question: SpringConfiguration { public SpringConfiguration withResourceGroup(String resourceGroup) { this.resourceGroup = resourceGroup; return this; } Boolean isPublic(); String getSubscriptionId(); String getResourceGroup(); String getClusterName(); String getAppName(); String getRuntimeVersion(); String getActiveDeploymentName(); Deployment getDeployment(); SpringConfiguration withPublic(Boolean isPublic); SpringConfiguration withSubscriptionId(String subscriptionId); SpringConfiguration withResourceGroup(String resourceGroup); SpringConfiguration withClusterName(String clusterName); SpringConfiguration withAppName(String appName); SpringConfiguration withRuntimeVersion(String runtimeVersion); SpringConfiguration withActiveDeploymentName(String deploymentName); SpringConfiguration withDeployment(Deployment deployment); }### Answer: @Test public void testWithResourceGroup() { final SpringConfiguration config = new SpringConfiguration(); config.withResourceGroup("resourceGroup1"); assertEquals("resourceGroup1", config.getResourceGroup()); }
### Question: SpringConfiguration { public SpringConfiguration withClusterName(String clusterName) { this.clusterName = clusterName; return this; } Boolean isPublic(); String getSubscriptionId(); String getResourceGroup(); String getClusterName(); String getAppName(); String getRuntimeVersion(); String getActiveDeploymentName(); Deployment getDeployment(); SpringConfiguration withPublic(Boolean isPublic); SpringConfiguration withSubscriptionId(String subscriptionId); SpringConfiguration withResourceGroup(String resourceGroup); SpringConfiguration withClusterName(String clusterName); SpringConfiguration withAppName(String appName); SpringConfiguration withRuntimeVersion(String runtimeVersion); SpringConfiguration withActiveDeploymentName(String deploymentName); SpringConfiguration withDeployment(Deployment deployment); }### Answer: @Test public void testWithClusterName() { final SpringConfiguration config = new SpringConfiguration(); config.withClusterName("clusterName1"); assertEquals("clusterName1", config.getClusterName()); }
### Question: SpringConfiguration { public SpringConfiguration withAppName(String appName) { this.appName = appName; return this; } Boolean isPublic(); String getSubscriptionId(); String getResourceGroup(); String getClusterName(); String getAppName(); String getRuntimeVersion(); String getActiveDeploymentName(); Deployment getDeployment(); SpringConfiguration withPublic(Boolean isPublic); SpringConfiguration withSubscriptionId(String subscriptionId); SpringConfiguration withResourceGroup(String resourceGroup); SpringConfiguration withClusterName(String clusterName); SpringConfiguration withAppName(String appName); SpringConfiguration withRuntimeVersion(String runtimeVersion); SpringConfiguration withActiveDeploymentName(String deploymentName); SpringConfiguration withDeployment(Deployment deployment); }### Answer: @Test public void testWithAppName() { final SpringConfiguration config = new SpringConfiguration(); config.withAppName("appName1"); assertEquals("appName1", config.getAppName()); }
### Question: SpringConfiguration { public SpringConfiguration withRuntimeVersion(String runtimeVersion) { this.runtimeVersion = runtimeVersion; return this; } Boolean isPublic(); String getSubscriptionId(); String getResourceGroup(); String getClusterName(); String getAppName(); String getRuntimeVersion(); String getActiveDeploymentName(); Deployment getDeployment(); SpringConfiguration withPublic(Boolean isPublic); SpringConfiguration withSubscriptionId(String subscriptionId); SpringConfiguration withResourceGroup(String resourceGroup); SpringConfiguration withClusterName(String clusterName); SpringConfiguration withAppName(String appName); SpringConfiguration withRuntimeVersion(String runtimeVersion); SpringConfiguration withActiveDeploymentName(String deploymentName); SpringConfiguration withDeployment(Deployment deployment); }### Answer: @Test public void testWithRuntimeVersion() { final SpringConfiguration config = new SpringConfiguration(); config.withRuntimeVersion("runtimeVersion1"); assertEquals("runtimeVersion1", config.getRuntimeVersion()); }
### Question: SpringConfiguration { public SpringConfiguration withDeployment(Deployment deployment) { this.deployment = deployment; return this; } Boolean isPublic(); String getSubscriptionId(); String getResourceGroup(); String getClusterName(); String getAppName(); String getRuntimeVersion(); String getActiveDeploymentName(); Deployment getDeployment(); SpringConfiguration withPublic(Boolean isPublic); SpringConfiguration withSubscriptionId(String subscriptionId); SpringConfiguration withResourceGroup(String resourceGroup); SpringConfiguration withClusterName(String clusterName); SpringConfiguration withAppName(String appName); SpringConfiguration withRuntimeVersion(String runtimeVersion); SpringConfiguration withActiveDeploymentName(String deploymentName); SpringConfiguration withDeployment(Deployment deployment); }### Answer: @Test public void testWithDeployment() { final SpringConfiguration config = new SpringConfiguration(); final Deployment deploy = Mockito.mock(Deployment.class); config.withDeployment(deploy); assertEquals(deploy, config.getDeployment()); }
### Question: Deployment { public Deployment withCpu(Integer cpu) { this.cpu = cpu; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }### Answer: @Test public void testWithCpu() { final Deployment deploy = new Deployment(); deploy.withCpu(1); assertEquals(1, (int) deploy.getCpu()); }
### Question: Deployment { public Deployment withMemoryInGB(Integer memoryInGB) { this.memoryInGB = memoryInGB; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }### Answer: @Test public void testWithMemoryInGB() { final Deployment deploy = new Deployment(); deploy.withMemoryInGB(2); assertEquals(2, (int) deploy.getMemoryInGB()); }
### Question: Deployment { public Deployment withInstanceCount(Integer instanceCount) { this.instanceCount = instanceCount; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }### Answer: @Test public void testWithInstanceCount() { final Deployment deploy = new Deployment(); deploy.withInstanceCount(3); assertEquals(3, (int) deploy.getInstanceCount()); }
### Question: Deployment { public Deployment withDeploymentName(String deploymentName) { this.deploymentName = deploymentName; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }### Answer: @Test public void testWithDeploymentName() { final Deployment deploy = new Deployment(); deploy.withDeploymentName("deploymentName1"); assertEquals("deploymentName1", deploy.getDeploymentName()); }
### Question: Deployment { public Deployment withJvmOptions(String jvmOptions) { this.jvmOptions = jvmOptions; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }### Answer: @Test public void testWithJvmOptions() { final Deployment deploy = new Deployment(); deploy.withJvmOptions("jvmOptions1"); assertEquals("jvmOptions1", deploy.getJvmOptions()); }
### Question: RunMojo extends AbstractFunctionMojo { @Override protected void doExecute() throws AzureExecutionException { final CommandHandler commandHandler = new CommandHandlerImpl(); checkStageDirectoryExistence(); checkRuntimeExistence(commandHandler); checkRuntimeCompatibility(commandHandler); runFunctions(commandHandler); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); }### Answer: @Test public void doExecute() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); doNothing().when(mojoSpy).checkStageDirectoryExistence(); doNothing().when(mojoSpy).checkRuntimeExistence(any(CommandHandler.class)); doNothing().when(mojoSpy).runFunctions(any(CommandHandler.class)); mojoSpy.doExecute(); verify(mojoSpy, times(1)).checkStageDirectoryExistence(); verify(mojoSpy, times(1)).checkRuntimeExistence(any(CommandHandler.class)); verify(mojoSpy, times(1)).runFunctions(any(CommandHandler.class)); }
### Question: Deployment { public Deployment withEnvironment(Map<String, String> environment) { this.environment = environment; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }### Answer: @Test public void testWithEnvironment() { final Deployment deploy = new Deployment(); deploy.withEnvironment(Collections.singletonMap("foo", "bar")); assertEquals("bar", deploy.getEnvironment().get("foo")); }
### Question: Deployment { public Deployment withResources(List<Resource> resources) { this.resources = resources; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }### Answer: @Test public void testWithResources() { final Deployment deploy = new Deployment(); deploy.withResources(ResourcesUtils.getDefaultResources()); assertEquals(1, deploy.getResources().size()); assertEquals("*.jar", deploy.getResources().get(0).getIncludes().get(0)); }
### Question: AppSettings extends BaseSettings { public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } String getSubscriptionId(); void setSubscriptionId(String subscriptionId); String getClusterName(); void setClusterName(String clusterName); String getAppName(); void setAppName(String appName); String isPublic(); void setPublic(String isPublic); }### Answer: @Test public void testSetSubscriptionId() { final AppSettings app = new AppSettings(); app.setSubscriptionId("subscriptionId1"); assertEquals("subscriptionId1", app.getSubscriptionId()); }
### Question: AppSettings extends BaseSettings { public void setClusterName(String clusterName) { this.clusterName = clusterName; } String getSubscriptionId(); void setSubscriptionId(String subscriptionId); String getClusterName(); void setClusterName(String clusterName); String getAppName(); void setAppName(String appName); String isPublic(); void setPublic(String isPublic); }### Answer: @Test public void testSetClusterName() { final AppSettings app = new AppSettings(); app.setClusterName("clusterName1"); assertEquals("clusterName1", app.getClusterName()); }
### Question: AppSettings extends BaseSettings { public void setAppName(String appName) { this.appName = appName; } String getSubscriptionId(); void setSubscriptionId(String subscriptionId); String getClusterName(); void setClusterName(String clusterName); String getAppName(); void setAppName(String appName); String isPublic(); void setPublic(String isPublic); }### Answer: @Test public void testSetAppName() { final AppSettings app = new AppSettings(); app.setAppName("appName1"); assertEquals("appName1", app.getAppName()); }
### Question: RequestParams { public static Builder builder (String resource) { return new Builder(resource); } RequestParams( String resource, String primaryKey, String primaryKeyValue, String column, String columnValue, String query, List<NameValuePair> queryArgs, List<NameValuePair> insert, List<NameValuePair> update, Integer page, Integer limit, Integer offset, String sort, String direction); static Builder builder(String resource); String getPath(final String root, final String alias); NameValuePair[] getParameters(); String getParametersAsQueryParams(); UrlEncodedFormEntity getFormBody(); StringEntity getJSONBody(); String toJSON(final List<NameValuePair> params); String getColumn(); String getColumnValue(); String getResource(); String getPrimaryKey(); String getPrimaryKeyValue(); Integer getPage(); Integer getLimit(); Integer getOffset(); String getSort(); String getDirection(); String getQuery(); List<NameValuePair> getQueryArgs(); List<NameValuePair> getInsert(); List<NameValuePair> getUpdate(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testRead_errors () { assertThrows(IllegalStateException.class, () -> RequestParams.builder(resource).value("x")); } @Test public void testDynamicQuery_errors () { assertThrows(IllegalArgumentException.class, () -> RequestParams.builder(resource).dynamicQuery("invalid")); assertThrows(IllegalArgumentException.class, () -> RequestParams.builder(resource).dynamicQuery("Find")); assertThrows(IllegalStateException.class, () -> RequestParams.builder(resource).addQueryParam("bar")); }
### Question: TkIndex implements Take { @Override public Response act(final Request req) throws IOException { return new RsPage( "/xsl/account.xsl", this.base, new RqWithDefaultHeader(req, HttpHeaders.ACCEPT, "text/xml"), new XeLink("save-email", "/acc/save") ); } TkIndex(final Base bse); @Override Response act(final Request req); }### Answer: @Test public void rendersPage() throws Exception { final Base base = new MkBase(); final String alias = "test"; final String urn = "urn:test:1"; base.user(URN.create(urn)).aliases().add(alias); MatcherAssert.assertThat( new RsPrint( new TkIndex(base).act(new RqWithAuth(urn)) ).printBody(), XhtmlMatchers.hasXPaths( "/page/alias/email", "/page/links/link[@rel='save-email']/@href" ) ); }
### Question: PsTwice implements Pass { @Override public Opt<Identity> enter(final Request req) throws IOException { Opt<Identity> user = new Opt.Empty<>(); if (this.fst.enter(req).has()) { user = this.snd.enter(req); } return user; } PsTwice(final Pass first, final Pass second); @Override Opt<Identity> enter(final Request req); @Override Response exit(final Response response, final Identity identity); }### Answer: @Test public void returnsSecondIdentity() throws Exception { MatcherAssert.assertThat( new PsTwice( new PsFake(true), new PsLogout() ).enter(new RqFake()).get(), Matchers.is(Identity.ANONYMOUS) ); } @Test public void returnsEmptyIdentity() throws Exception { MatcherAssert.assertThat( new PsTwice( new PsFake(false), new PsLogout() ).enter(new RqFake()).has(), Matchers.equalTo(false) ); }
### Question: PsTwice implements Pass { @Override public Response exit(final Response response, final Identity identity) throws IOException { return this.snd.exit(response, identity); } PsTwice(final Pass first, final Pass second); @Override Opt<Identity> enter(final Request req); @Override Response exit(final Response response, final Identity identity); }### Answer: @Test public void returnsCorrectResponseOnExit() throws Exception { MatcherAssert.assertThat( new PsTwice( new PsFake(true), new PsLogout() ).exit(new RsEmpty(), Identity.ANONYMOUS) .head().iterator().next(), Matchers.containsString("HTTP/1.1 200 O") ); }
### Question: TkFavicon implements Take { @Override public Response act(final Request req) throws IOException { final long unread = TkFavicon.unread(req); final int width = 64; final int height = 64; final BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB ); final Graphics graph = image.getGraphics(); graph.setColor(new Color(0x4b, 0x42, 0x50)); graph.fillRect(0, 0, width, height); if (unread > 0L) { final String text; if (unread >= (long) Tv.HUNDRED) { text = "99"; } else { text = Long.toString(unread); } graph.setColor(Color.WHITE); graph.setFont(new Font(Font.SANS_SERIF, Font.BOLD, height / 2)); graph.drawString( text, width - width / Tv.TEN - graph.getFontMetrics().stringWidth(text), height - height / Tv.TEN ); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "gif", baos); return new RsWithType( new RsWithBody(baos.toByteArray()), "image/gif" ); } @Override Response act(final Request req); }### Answer: @Test public void buildsGifImage() throws Exception { MatcherAssert.assertThat( new RsPrint( new TkFavicon().act(new RqFake("GET", "/?unread=44")) ).printBody(), Matchers.notNullValue() ); }
### Question: Ports { public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } } private Ports(); static int allocate(); static void release(final int port); }### Answer: @Test public void allocatesDifferentNumbersWithDifferentPorts() throws Exception { final int porta = Ports.allocate(); final int portb = Ports.allocate(); final int portc = Ports.allocate(); MatcherAssert.assertThat(porta, Matchers.not(portb)); MatcherAssert.assertThat(porta, Matchers.not(portc)); MatcherAssert.assertThat(portb, Matchers.not(portc)); } @Test public void allocatesDifferentNumbersWithSamePorts() throws Exception { final int porta = Ports.allocate(); final int portb = Ports.allocate(); final int portc = Ports.allocate(); MatcherAssert.assertThat(porta, Matchers.not(portb)); MatcherAssert.assertThat(porta, Matchers.not(portc)); MatcherAssert.assertThat(portb, Matchers.not(portc)); }
### Question: EmCatch { public void start() { final Thread monitor = new Thread( new Runnable() { @Override public void run() { EmCatch.this.mainLoop(); } } ); monitor.setDaemon(true); monitor.start(); } EmCatch(final Action act, final String usr, final String pass, final String hst, final int prt, final long prd); void start(); }### Answer: @Test public void readsInboxPeriodically() throws Exception { final GreenMail mail = new GreenMail( new ServerSetup(Ports.allocate(), null, "pop3") ); mail.start(); final ServerSetup setup = mail.getPop3().getServerSetup(); final String login = "to"; final String from = "[email protected]"; final String to = "[email protected]"; final String password = "soooosecret"; final String subject = GreenMailUtil.random(); final String body = GreenMailUtil.random(); final GreenMailUser user = mail.setUser(login, password); new EmCatch( new EmCatch.Action() { @Override public void run(final Message msg) { MatcherAssert.assertThat(msg, Matchers.notNullValue()); try { MatcherAssert.assertThat( msg.getSubject(), Matchers.equalTo(subject) ); MatcherAssert.assertThat( msg.getFrom()[0].toString(), Matchers.equalTo(from) ); MatcherAssert.assertThat( msg.getAllRecipients()[0].toString(), Matchers.equalTo(to) ); } catch (final MessagingException ex) { throw new IllegalStateException(ex); } } }, login, password, setup.getBindAddress(), setup.getPort(), 500L ).start(); final MimeMessage message = GreenMailUtil.createTextEmail( to, from, subject, body, setup ); user.deliver(message); MatcherAssert.assertThat( mail.getReceivedMessages().length, Matchers.equalTo(1) ); Thread.sleep(1000); Ports.release(setup.getPort()); mail.stop(); }
### Question: EmAlias implements Alias { @Override public String email() throws IOException { return this.origin.email(); } EmAlias(final Alias org, final Postman pst); @Override String name(); @Override URI photo(); @Override Locale locale(); @Override void photo(final URI uri); @Override String email(); @Override void email(final String email); @Override void email(final String email, final String urn, final Bout bout); @Override void email(final String email, final String link); @Override Inbox inbox(); }### Answer: @Test public void sendsConfirmationEmail() throws Exception { final Postman postman = Mockito.mock(Postman.class); final Alias alias = new EmAlias(new MkBase().randomAlias(), postman); alias.email("[email protected]", "netbout.com/test/verification/link"); final ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class); Mockito.verify(postman).send(captor.capture()); final Message msg = captor.getValue().unwrap(); MatcherAssert.assertThat(msg.getFrom().length, Matchers.is(1)); MatcherAssert.assertThat( msg.getSubject(), Matchers.equalTo("Netbout email verification") ); MatcherAssert.assertThat( msg.getAllRecipients()[0].toString(), Matchers.containsString("mihai@test") ); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); MimeMultipart.class.cast(msg.getContent()).writeTo(baos); final String content = new String(baos.toByteArray(), "UTF-8"); MatcherAssert.assertThat( content, Matchers.containsString( "<p>Hi,<br />Your notification e-mail address" ) ); MatcherAssert.assertThat( content, Matchers.containsString( "<a href=\"netbout.com/test/verification/link\">here</a>" ) ); }
### Question: MkMessages implements Messages { @Override public void post(final String text) throws IOException { try { new JdbcSession(this.sql.source()) .sql("INSERT INTO message (bout, text, author) VALUES (?, ?, ?)") .set(this.bout) .set(text) .set(this.self) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } new TouchBout(this.sql, this.bout).act(); } MkMessages(final Sql src, final long bot, final String slf); @Override void post(final String text); @Override long unread(); @Override Pageable<Message> jump(final long number); @Override Iterable<Message> iterate(); @Override Iterable<Message> search(final String term); }### Answer: @Test public void changesUpdateAttribute() throws Exception { final Bout bout = new MkBase().randomBout(); final Messages messages = bout.messages(); final Long last = bout.updated().getTime(); messages.post("hi"); Thread.sleep(Tv.HUNDRED); MatcherAssert.assertThat( bout.updated().getTime(), Matchers.greaterThan(last) ); }
### Question: MkInbox implements Inbox { @Override public long start() throws IOException { try { final Long number = new JdbcSession(this.sql.source()) .sql("INSERT INTO bout (title) VALUES (?)") .set("untitled") .insert(new SingleOutcome<Long>(Long.class)); this.bout(number).friends().invite(this.self); return number; } catch (final SQLException ex) { throw new IOException(ex); } } MkInbox(final Sql src, final String name); @Override long start(); @Override long unread(); @Override Bout bout(final long number); @Override Pageable<Bout> jump(final long number); @Override Iterable<Bout> iterate(); @Override Iterable<Bout> search(final String term); }### Answer: @Test public final void testStart() throws IOException { final String name = "current-name"; final Sql sql = new H2Sql(); final Aliases aliases = new MkUser( sql, URN.create( String.format( "urn:test:%d", new SecureRandom().nextInt(Integer.MAX_VALUE) ) ) ).aliases(); aliases.add(name); final Alias alias = aliases.iterate().iterator().next(); alias.email(String.format("%[email protected]", alias.name())); final MkInbox inbox = new MkInbox(sql, name); final Bout bout = inbox.bout(inbox.start()); MatcherAssert.assertThat( bout.friends().iterate(), Matchers.hasItem(new Friend.HasAlias(Matchers.is(name))) ); }
### Question: MkAlias implements Alias { @Override public String email() throws IOException { try { return new JdbcSession(this.sql.source()) .sql("SELECT email FROM alias WHERE name = ?") .set(this.label) .select(new SingleOutcome<String>(String.class)); } catch (final SQLException ex) { throw new IOException(ex); } } MkAlias(final Sql src, final String name); @Override String name(); @Override URI photo(); @Override Locale locale(); @Override void photo(final URI uri); @Override String email(); @Override void email(final String email); @Override void email(final String email, final String urn, final Bout bout); @Override void email(final String email, final String link); @Override Inbox inbox(); }### Answer: @Test public void savesAndReadsEmail() throws Exception { final Alias alias = new MkBase().randomAlias(); MatcherAssert.assertThat(alias.email(), Matchers.notNullValue()); final String email = "[email protected]"; alias.email(email); MatcherAssert.assertThat(alias.email(), Matchers.equalTo(email)); }
### Question: MkBase implements Base { public Bout randomBout() throws IOException { final Inbox inbox = this.randomAlias().inbox(); final Bout bout = inbox.bout(inbox.start()); bout.rename( String.format( "random title %d", MkBase.RANDOM.nextInt(Integer.MAX_VALUE) ) ); return bout; } MkBase(); MkBase(final Sql src); @Override User user(final URN urn); @Override void close(); Alias randomAlias(); Bout randomBout(); }### Answer: @Test public void startsBoutAndTalks() throws Exception { final Messages messages = new MkBase().randomBout().messages(); messages.post("How are you doing?"); MatcherAssert.assertThat( messages.iterate(), Matchers.hasItem( new Message.HasText(Matchers.containsString("are you")) ) ); }
### Question: TouchBout { public void act() throws IOException { try { new JdbcSession(this.sql.source()) .sql("UPDATE bout SET updated = CURRENT_TIMESTAMP WHERE number = ?") .set(this.bout) .update(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } TouchBout(final Sql src, final long bot); void act(); }### Answer: @Test public void changesUpdateAttribute() throws Exception { final Sql sql = new H2Sql(); final Bout bout = new MkBase(sql).randomBout(); final Long last = bout.updated().getTime(); new TouchBout(sql, bout.number()).act(); Thread.sleep(Tv.HUNDRED); MatcherAssert.assertThat( bout.updated().getTime(), Matchers.greaterThan(last) ); }
### Question: MkFriends implements Friends { @Override public void invite(final String friend) throws IOException { try { final boolean exists = new JdbcSession(this.sql.source()) .sql("SELECT name FROM alias WHERE name = ?") .set(friend) .select(Outcome.NOT_EMPTY); if (!exists) { throw new Friends.UnknownAliasException( String.format("alias '%s' doesn't exist", friend) ); } new JdbcSession(this.sql.source()) .sql("INSERT INTO friend (bout, alias, subscription) VALUES (?, ?, ?)") .set(this.bout) .set(friend) .set(true) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } MkFriends(final Sql src, final long bot); @Override void invite(final String friend); @Override void kick(final String friend); @Override Iterable<Friend> iterate(); }### Answer: @Test(expected = Friends.UnknownAliasException.class) public void inviteFailsOnUnknownAlias() throws Exception { new MkBase().randomBout().friends().invite("NoSuchFriend"); }
### Question: XeMethod implements Method { @Override public void attribute(final String name, final String seal) { this.dirs.xpath(this.start) .strict(1) .addIf("attributes") .xpath( String.format( "%s/attributes[not(attribute=%s)]", this.start, XeOntology.escapeXPath(name) ) ) .add("attribute").set(name) .xpath( String.format( "%s/attributes/attribute[.=%s]", this.start, XeOntology.escapeXPath(name) ) ) .strict(1) .attr("seal", seal); } XeMethod(final Directives directives, final String xpath); @Override void attribute(final String name, final String seal); @Override Nfr nfr(final String name); @Override void sign(final String text); @Override void object(final String name); @Override void result(final String name); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void input(final String name); @Override void explain(final String info); @Override void mention(final int where); }### Answer: @Test public void setsAttributes() throws Exception { final Directives dirs = new Directives().add("x"); final Method method = new XeMethod(dirs, "/x"); final String name = "attr-1"; method.attribute(name, ""); method.attribute(name, "ffa7ed"); method.attribute("another", "123456"); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPaths( "/x/attributes[count(attribute)=2]", "/x/attributes[attribute='attr-1' and attribute='another']", "/x/attributes/attribute[.='attr-1' and @seal='ffa7ed']" ) ); }
### Question: XeOntology implements Ontology { @Override public Type type(final String name) { this.root("types") .xpath( String.format( "/spec/types[not(type/name=%s)]", XeOntology.escapeXPath(name) ) ) .add("type").add("name").set(name); return new XeType( this.dirs, String.format( "/spec/types/type[name=%s]", XeOntology.escapeXPath(name) ) ); } @Override Type type(final String name); @Override Method method(final String name); @Override Page page(final String name); @Override Acronym acronym(final String name); @Override Iterator<Directive> iterator(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String escapeXPath(final String text); }### Answer: @Test public void manipulatesWithTypesAndUseCases() throws Exception { final XeOntology onto = new XeOntology(); final Type type = onto.type("First"); type.explain("first text"); type.parent("Root"); type.slot("one").assign("Emp"); onto.type("Second").explain("second text"); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(onto).xml()), XhtmlMatchers.hasXPaths( "/spec", "/spec/types/type[name='First']", "/spec/types/type[name='Second']" ) ); } @Test public void avoidsDuplication() throws Exception { final XeOntology onto = new XeOntology(); final String name = "Alpha"; onto.type(name); onto.type(name); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(onto).xml()), XhtmlMatchers.hasXPath("/spec/types[count(type)=1]") ); }
### Question: XeOntology implements Ontology { @Override public Method method(final String name) { this.root("methods") .xpath( String.format( "/spec/methods[not(method/id=%s)]", XeOntology.escapeXPath(name) ) ) .add("method").add("id").set(name); return new XeMethod( this.dirs, String.format( "/spec/methods/method[id=%s]", XeOntology.escapeXPath(name) ) ); } @Override Type type(final String name); @Override Method method(final String name); @Override Page page(final String name); @Override Acronym acronym(final String name); @Override Iterator<Directive> iterator(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String escapeXPath(final String text); }### Answer: @Test public void avoidsDuplicationOfMethods() throws Exception { final XeOntology onto = new XeOntology(); final String name = "UC3"; onto.method(name); onto.method(name); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(onto).xml()), XhtmlMatchers.hasXPath("/spec/methods[count(method)=1]") ); }
### Question: XeFlow implements Flow { @Override public void binding(final String name, final String type) { this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath( String.format( "bindings[not(binding[name='%s' and type=%s])]", name, XeOntology.escapeXPath(type) ) ).add("binding").add("name").set(name).up().add("type").set(type); } XeFlow(final Directives directives, final String xpath); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void explain(final String info); }### Answer: @Test public void manipulatesWithBindings() throws Exception { final Directives dirs = new Directives().add("f"); final Flow flow = new XeFlow(dirs, "/f"); flow.binding("emp", "Employee"); flow.binding("one", "One"); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPaths( "/f/bindings/binding[name='emp' and type='Employee']", "/f/bindings/binding[name='one' and type='One']" ) ); } @Test public void avoidsDuplicateBindings() throws Exception { final Directives dirs = new Directives().add("f1"); final Flow flow = new XeFlow(dirs, "/f1"); for (int idx = 0; idx < Tv.FIVE; ++idx) { flow.binding("a", "alpha"); } MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPaths( "/f1/bindings[count(binding)=1]", "/f1/bindings/binding[name='a' and type='alpha']" ) ); }
### Question: Plant { @SuppressWarnings("PMD.ProhibitPublicStaticMethods") public static String svg(final String src) throws IOException { final String svg; if (SystemUtils.IS_OS_WINDOWS) { svg = "<p>SVG can't be rendered in Windows</p>"; } else { final SourceStringReader reader = new SourceStringReader(src); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); reader.generateImage(baos, new FileFormatOption(FileFormat.SVG)); svg = new XMLDocument( new String(baos.toByteArray()) ).nodes("/*").get(0).toString().replace("xmlns=\"\"", ""); } return svg; } private Plant(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String svg(final String src); }### Answer: @Test public void buildsSvg() throws IOException { Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS); MatcherAssert.assertThat( XhtmlMatchers.xhtml( Plant.svg("@startuml\nBob -> Alice : hello\n@enduml\n") ), XhtmlMatchers.hasXPath(" ); }
### Question: CascadingRule implements Rule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> enforce(final String text) { final String[] lines = StringUtils.splitPreserveAllTokens(text, '\n'); final Collection<Violation> violations = new LinkedList<>(); int indent = 0; for (int idx = 0; idx < lines.length; ++idx) { final int next = CascadingRule.indent(lines[idx]); if (indent > 0 && next > indent && next != indent + 2) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, while %d required: [%s]", next, indent + 2, lines[idx] ), idx + 1, next ) ); } indent = next; } return violations; } @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") Collection<Violation> enforce(final String text); }### Answer: @Test public void checksInput() throws Exception { MatcherAssert.assertThat( new CascadingRule().enforce("hey\n works\n fine\nstart"), Matchers.empty() ); } @Test public void checksInvalidInput() throws Exception { MatcherAssert.assertThat( new CascadingRule().enforce( "\n\n\n hey\n three!" ).iterator().next().line(), Matchers.equalTo(Tv.FIVE) ); }
### Question: Main { private Main() { } private Main(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static void main(final String... args); }### Answer: @Test public void displaysVersionNumber() throws Exception { Main.main(new String[]{"-v"}); MatcherAssert.assertThat( this.out.toString(), Matchers.containsString("-SNAPSHOT") ); } @Test public void rendersHelpMessage() throws Exception { Main.main(new String[] {"-h"}); MatcherAssert.assertThat( this.out.toString(), Matchers.containsString("Usage:") ); } @Test public void compilesRequsSources() throws Exception { final File input = this.temp.newFolder(); final File output = this.temp.newFolder(); FileUtils.write( new File(input, "employee.req"), "Employee is a \"user of the system\".", StandardCharsets.UTF_8 ); Main.main( new String[] { "-i", input.getAbsolutePath(), "-o", output.getAbsolutePath(), } ); MatcherAssert.assertThat( this.out.toString(), Matchers.containsString("compiled and saved to") ); MatcherAssert.assertThat( XhtmlMatchers.xhtml( FileUtils.readFileToString( new File(output, "requs.xml"), StandardCharsets.UTF_8 ) ), XhtmlMatchers.hasXPaths("/spec/types/type[name='Employee']") ); }
### Question: InstantRs extends BaseRs { @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Loggable @SuppressWarnings("PMD.AvoidCatchingGenericException") public String post(@NotNull @FormParam("text") final String text) throws IOException { final File input = Files.createTempDir(); FileUtils.write( new File(input, "in.req"), text, StandardCharsets.UTF_8 ); final File output = Files.createTempDir(); try { new org.requs.Compiler(input, output).compile(); final XML xml = new XMLDocument( FileUtils.readFileToString( new File(output, "requs.xml"), StandardCharsets.UTF_8 ) ); final XSL xsl = new XSLDocument( FileUtils.readFileToString( new File(output, "requs.xsl"), StandardCharsets.UTF_8 ) ); return Json.createObjectBuilder() .add("spec", xml.nodes("/spec").get(0).toString()) .add("html", xsl.applyTo(xml)) .build().toString(); } catch (final RuntimeException ex) { throw new WebApplicationException( Response.status(HttpURLConnection.HTTP_INTERNAL_ERROR) .entity(ExceptionUtils.getStackTrace(ex)) .build() ); } finally { FileUtils.deleteDirectory(input); FileUtils.deleteDirectory(output); } } @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Loggable @SuppressWarnings("PMD.AvoidCatchingGenericException") String post(@NotNull @FormParam("text") final String text); }### Answer: @Test public void processesRequsSpec() throws Exception { final InstantRs res = new InstantRs(); res.setUriInfo(new UriInfoMocker().mock()); res.setHttpHeaders(new HttpHeadersMocker().mock()); final SecurityContext sec = Mockito.mock(SecurityContext.class); res.setSecurityContext(sec); final String json = res.post("User is a \"type\"."); MatcherAssert.assertThat( Json.createReader(new StringReader(json)) .readObject().getString("spec"), XhtmlMatchers.hasXPath("/spec/types/type[name='User']") ); }
### Question: IndexRs extends BaseRs { @GET @Path("/") public Response index() throws Exception { return new PageBuilder() .stylesheet("/xsl/index.xsl") .build(DemoPage.class) .init(this) .render() .build(); } @GET @Path("/") Response index(); }### Answer: @Test public void rendersFrontPage() throws Exception { final IndexRs res = new IndexRs(); res.setUriInfo(new UriInfoMocker().mock()); res.setHttpHeaders(new HttpHeadersMocker().mock()); final SecurityContext sec = Mockito.mock(SecurityContext.class); res.setSecurityContext(sec); final Response response = res.index(); MatcherAssert.assertThat( JaxbConverter.the(response.getEntity()), XhtmlMatchers.hasXPaths( "/page/millis", "/page/version/name" ) ); }
### Question: IndentationRule implements LineRule { @Override public Collection<Violation> check(final String line) { int indent; for (indent = 0; indent < line.length(); ++indent) { if (line.charAt(indent) != ' ') { break; } } final Collection<Violation> violations = new LinkedList<>(); if (indent % 2 != 0) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, must be either %d or %d: [%s]", indent, indent >> 1 << 1, indent + 1 >> 1 << 1, line ), 0, indent ) ); } return violations; } @Override Collection<Violation> check(final String line); }### Answer: @Test public void checksInput() throws Exception { MatcherAssert.assertThat( new IndentationRule().check(" works fine"), Matchers.empty() ); } @Test public void checksInvalidInput() throws Exception { MatcherAssert.assertThat( new IndentationRule().check(" works fine"), Matchers.not(Matchers.empty()) ); }
### Question: RegexRule implements LineRule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> check(final String line) { final Pattern ptn = Pattern.compile(this.regex); final Matcher matcher = ptn.matcher(line); final Collection<Violation> violations = new LinkedList<>(); while (matcher.find()) { violations.add( new Violation.Simple( String.format("%s: [%s]", this.text, line), 0, matcher.start() + 1 ) ); } return violations; } RegexRule(final String rgx, final String txt); @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") Collection<Violation> check(final String line); }### Answer: @Test public void checksInput() throws Exception { MatcherAssert.assertThat( new RegexRule("[a-z]+", "").check("abjkljeklsf"), Matchers.not(Matchers.empty()) ); } @Test public void checksInvalidInput() throws Exception { MatcherAssert.assertThat( new RegexRule("[0-9]", "").check("broken input"), Matchers.empty() ); }
### Question: XeSignature implements Signature { @Override public void sign(final String text) { this.dirs.xpath(this.start).strict(1) .add("signature").set(text); } XeSignature(final Directives directives, final String xpath); @Override void sign(final String text); @Override void object(final String name); @Override void result(final String name); @Override void input(final String name); @Override void explain(final String info); }### Answer: @Test public void signsMethod() throws Exception { final Directives dirs = new Directives().add("s"); final Signature signature = new XeSignature(dirs, "/s"); signature.sign("\"informal one\""); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPaths( "/s[signature='\"informal one\"']" ) ); }
### Question: XeMethod implements Method { @Override public Step step(final int number) { return this.flow.step(number); } XeMethod(final Directives directives, final String xpath); @Override void attribute(final String name, final String seal); @Override Nfr nfr(final String name); @Override void sign(final String text); @Override void object(final String name); @Override void result(final String name); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void input(final String name); @Override void explain(final String info); @Override void mention(final int where); }### Answer: @Test public void avoidsDuplicateSteps() throws Exception { final Directives dirs = new Directives().add("mtd"); final Method method = new XeMethod(dirs, "/mtd"); method.step(1); method.step(1); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPath("/mtd/steps[count(step)=1]") ); }
### Question: ParametricState { public ParametricState(State state) { Position[] stateMemberPositionArray = state.getMemberPositions(); int memberPositionCount = stateMemberPositionArray.length; memberPositionBoundaryOffsetArray = new int[memberPositionCount]; memberPositionEArray = new int[memberPositionCount]; memberPositionTArray = new boolean[memberPositionCount]; for(int i = 0; i < memberPositionCount; i++) { memberPositionBoundaryOffsetArray[i] = stateMemberPositionArray[i].getI() - stateMemberPositionArray[0].getI(); memberPositionEArray[i] = stateMemberPositionArray[i].getE(); memberPositionTArray[i] = stateMemberPositionArray[i].getT(); } } ParametricState(State state); ParametricState(State state, int transitionBoundaryOffset); int getLargestPositionOffset(); int getTransitionBoundaryOffset(); State createActualState(int minimalBoundary); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test(dataProvider = "parametricStateTestDP") public void parametricStateTest(int originalBase, State s) { ParametricState ts = new ParametricState(s); State s1 = ts.createActualState(originalBase); assert Arrays.equals(s.getMemberPositions(), s1.getMemberPositions()); }
### Question: ADistribution implements IDistribution<SPACE> { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getDistributionConfiguration().overrideConfiguration(jsonObject); } ADistribution(); @Override List<SPACE> generateSamples(int numberOfSamples); abstract CONFIG createDefaultDistributionConfiguration(); @Override ADistributionConfiguration getDefaultDistributionConfiguration(); @Override @SuppressWarnings("unchecked") void setDistributionConfiguration(ADistributionConfiguration algorithmConfiguration); @Override @SuppressWarnings("unchecked") CONFIG getDistributionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override String toString(); }### Answer: @Test @Override public void testWrongParameters() throws JsonParsingFailedException { List<Pair<String, JsonObject>> listOfPairsOfStringAndJsonObjects = getWrongParameters(); for (int i = 0; i < listOfPairsOfStringAndJsonObjects.size(); i++) { IDistribution<SPACE> distribution = getDistribution(); try { distribution.setParameters(listOfPairsOfStringAndJsonObjects.get(i).getSecond()); fail(String.format(ERROR_INCORRECT_PARAMETER_ACCEPTED, listOfPairsOfStringAndJsonObjects.get(i).getSecond())); } catch (ParameterValidationFailedException e) { Assert.assertEquals(ERROR_WRONG_OUTPUT, listOfPairsOfStringAndJsonObjects.get(i).getFirst(), e.getMessage()); } } } @Test @Override public void testCorrectParameters() throws JsonParsingFailedException { List<JsonObject> listOfJsonObjects = getCorrectParameters(); for (int i = 0; i < listOfJsonObjects.size(); i++) { IDistribution<SPACE> distribution = getDistribution(); try { distribution.setParameters(listOfJsonObjects.get(i)); } catch (ParameterValidationFailedException e) { fail(String.format(ERROR_CORRECT_PARAMETER_NOT_ACCEPTED, listOfJsonObjects.get(i))); } } }
### Question: RunCompleteToolChainCommand extends ACommand { public RunCompleteToolChainCommand(RunCompleteToolChainCommandConfiguration commandConfiguration) { super(ECommand.RUN_COMPLETE_TOOLCHAIN.getCommandIdentifier()); this.commandConfiguration = commandConfiguration; toolChainCommands = new ArrayList<>(); commandExecutionSuccessPairs = new ArrayList<>(); inputControl = InputControl.getInputControl(); systemStatus = SystemStatus.getSystemStatus(); } RunCompleteToolChainCommand(RunCompleteToolChainCommandConfiguration commandConfiguration); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); }### Answer: @Test public void testRunCompleteToolChainCommand() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String command[] = { ECommand.RUN_COMPLETE_TOOLCHAIN.getCommandIdentifier(), PARAMETER_CONFIG + getTestRessourcePathFor(CORRECT_SYSTEM_CONFIG_JSON) }; TestUtils.simulateCommandLineInput(command); assertCorrectCommandResultAsLatestInCommandHistory(); }
### Question: InputControl implements Observer { @Override public void update(Observable o, Object arg) { if (o instanceof CommandLineParserView && arg instanceof String[]) { String[] userInput = (String[]) arg; handleUserInput(userInput); } else { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_UPDATE, o, arg)); } } private InputControl(); static InputControl getInputControl(); @Override void update(Observable o, Object arg); void printUsage(); void simulateUserInput(String[] userInput); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testUpdateFailureWithWrongObservable() { inputControl.update(new DetermineApplicableAlgorithmsCommandHandler(), StringUtils.EMPTY_STRING); } @Test(expected = UnsupportedOperationException.class) public void testUpdateFailureWithWrongArgument() { inputControl.update(CommandLineParserView.getCommandLineParserView(), new Exception()); }
### Question: ADatasetParser implements IDatasetParser { @Override public IDataset<?, ?, ?> parse(DatasetFile file) throws ParsingFailedException { return parsePartialOf(file, Integer.MAX_VALUE); } @Override IDataset<?, ?, ?> parse(DatasetFile file); @Override IDataset<?, ?, ?> parsePartialOf(DatasetFile file, int amountOfInstances); static Ranking parseRelativeRanking(String ranking); static final String ITEM_MARKER; }### Answer: @Test public void testParseInvalidDataset() { List<DatasetFile> datasets = getInvalidDatasets(); for (int i = 0; i < datasets.size(); i++) { try { DatasetFile datasetFile = datasets.get(i); getDatasetParser().parse(datasetFile); fail(PARSING_FAILED_EXCEPTION_EXPECTED_BUT_NOT_FOUND); } catch (ParsingFailedException e) { } } } @Test public void testParseValidDataset() throws ParsingFailedException { List<DatasetFile> datasets = getValidDatasets(); for (int i = 0; i < datasets.size(); i++) { DatasetFile datasetFile = datasets.get(i); IDatasetParser parser = getDatasetParser(); parser.parse(datasetFile); validateDataset(i, parser.getDataset()); } }
### Question: AAlgorithm implements IAlgorithm { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getAlgorithmConfiguration().overrideConfiguration(jsonObject); } AAlgorithm(); AAlgorithm(String algorithmIdentifier); @Override AAlgorithmConfiguration getDefaultAlgorithmConfiguration(); @Override @SuppressWarnings("unchecked") void setAlgorithmConfiguration(AAlgorithmConfiguration algorithmConfiguration); @Override @SuppressWarnings("unchecked") CONFIG getAlgorithmConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override boolean equals(Object secondObject); @Override int hashCode(); @Override String toString(); }### Answer: @Test @Override public void testCorrectParameters() throws JsonParsingFailedException { List<JsonObject> listOfJsonObjects = getCorrectParameters(); for (int i = 0; i < listOfJsonObjects.size(); i++) { IAlgorithm algorithm = getAlgorithm(); try { algorithm.setParameters(listOfJsonObjects.get(i)); } catch (ParameterValidationFailedException e) { fail(String.format(ERROR_CORRECT_PARAMETER_NOT_ACCEPTED, listOfJsonObjects.get(i))); } } } @Test @Override public void testWrongParameters() throws JsonParsingFailedException { List<Pair<String, JsonObject>> listOfPairsOfStringAndJsonObjects = getWrongParameters(); for (int i = 0; i < listOfPairsOfStringAndJsonObjects.size(); i++) { IAlgorithm algorithm = getAlgorithm(); try { algorithm.setParameters(listOfPairsOfStringAndJsonObjects.get(i).getSecond()); fail(String.format(ERROR_INCORRECT_PARAMETER_ACCEPTED, listOfPairsOfStringAndJsonObjects.get(i).getSecond())); } catch (ParameterValidationFailedException e) { Assert.assertEquals(ERROR_WRONG_OUTPUT, e.getMessage(), listOfPairsOfStringAndJsonObjects.get(i).getFirst()); } } }
### Question: CategoryTreeNavigator { public void selectCategory(long selectedCategoryId) { Map<Long, Category> map = categories.asMap(); Category selectedCategory = map.get(selectedCategoryId); if (selectedCategory != null) { Stack<Long> path = new Stack<>(); Category parent = selectedCategory.parent; while (parent != null) { path.push(parent.id); parent = parent.parent; } while (!path.isEmpty()) { navigateTo(path.pop()); } this.selectedCategoryId = selectedCategoryId; } } CategoryTreeNavigator(DatabaseAdapter db); CategoryTreeNavigator(DatabaseAdapter db, long excludedTreeId); void selectCategory(long selectedCategoryId); void tagCategories(Category parent); boolean goBack(); boolean canGoBack(); boolean navigateTo(long categoryId); boolean isSelected(long categoryId); List<Category> getSelectedRoots(); void addSplitCategoryToTheTop(); void separateIncomeAndExpense(); long getExcludedTreeId(); static final long INCOME_CATEGORY_ID; static final long EXPENSE_CATEGORY_ID; public CategoryTree<Category> categories; public long selectedCategoryId; }### Answer: @Test public void should_select_startup_category() { long selectedCategoryId = categories.get("AA1").id; navigator.selectCategory(selectedCategoryId); assertEquals(selectedCategoryId, navigator.selectedCategoryId); assertSelected(selectedCategoryId, "A1", "AA1"); }
### Question: TransactionsTotalCalculator { public Total[] getTransactionsBalance() { WhereFilter filter = this.filter; if (filter.getAccountId() == -1) { filter = excludeAccountsNotIncludedInTotalsAndSplits(filter); } try (Cursor c = db.db().query(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, BALANCE_PROJECTION, filter.getSelection(), filter.getSelectionArgs(), BALANCE_GROUPBY, null, null)) { int count = c.getCount(); List<Total> totals = new ArrayList<Total>(count); while (c.moveToNext()) { long currencyId = c.getLong(0); long balance = c.getLong(1); Currency currency = CurrencyCache.getCurrency(db, currencyId); Total total = new Total(currency); total.balance = balance; totals.add(total); } return totals.toArray(new Total[totals.size()]); } } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); Total[] getTransactionsBalance(); Total getAccountTotal(); Total getBlotterBalanceInHomeCurrency(); Total getBlotterBalance(Currency toCurrency); Total getAccountBalance(Currency toCurrency, long accountId); static Total calculateTotalFromListInHomeCurrency(DatabaseAdapter db, List<TransactionInfo> list); static long[] calculateTotalFromList(DatabaseAdapter db, List<TransactionInfo> list, Currency toCurrency); static BigDecimal getAmountFromCursor(MyEntityManager em, Cursor c, Currency toCurrency, ExchangeRateProvider rates, int index); static BigDecimal getAmountFromTransaction(MyEntityManager em, TransactionInfo ti, Currency toCurrency, ExchangeRateProvider rates); static final String[] BALANCE_PROJECTION; static final String BALANCE_GROUPBY; static final String[] HOME_CURRENCY_PROJECTION; }### Answer: @Test public void should_calculate_blotter_total_in_multiple_currencies() { Total[] totals = c.getTransactionsBalance(); assertEquals(2, totals.length); assertEquals(-700, totals[0].balance); assertEquals(-230, totals[1].balance); }
### Question: CategoryTreeNavigator { public boolean navigateTo(long categoryId) { Category selectedCategory = findCategory(categoryId); if (selectedCategory != null) { selectedCategoryId = selectedCategory.id; if (selectedCategory.hasChildren()) { categoriesStack.push(categories); categories = selectedCategory.children; tagCategories(selectedCategory); return true; } } return false; } CategoryTreeNavigator(DatabaseAdapter db); CategoryTreeNavigator(DatabaseAdapter db, long excludedTreeId); void selectCategory(long selectedCategoryId); void tagCategories(Category parent); boolean goBack(); boolean canGoBack(); boolean navigateTo(long categoryId); boolean isSelected(long categoryId); List<Category> getSelectedRoots(); void addSplitCategoryToTheTop(); void separateIncomeAndExpense(); long getExcludedTreeId(); static final long INCOME_CATEGORY_ID; static final long EXPENSE_CATEGORY_ID; public CategoryTree<Category> categories; public long selectedCategoryId; }### Answer: @Test public void should_navigate_to_category() { long categoryId = categories.get("A").id; navigator.navigateTo(categoryId); assertSelected(categoryId, "A", "A1", "A2"); categoryId = categories.get("A1").id; navigator.navigateTo(categoryId); assertSelected(categoryId, "A1", "AA1"); categoryId = categories.get("AA1").id; navigator.navigateTo(categoryId); assertSelected(categoryId, "A1", "AA1"); }
### Question: IntegrityCheckRunningBalance implements IntegrityCheck { @Override public Result check() { if (isRunningBalanceBroken()) { return new Result(Level.ERROR, context.getString(R.string.integrity_error)); } else { return Result.OK; } } IntegrityCheckRunningBalance(Context context, DatabaseAdapter db); @Override Result check(); }### Answer: @Test public void should_detect_that_running_balance_is_broken() { TransactionBuilder.withDb(db).account(a1).amount(1000).create(); TransactionBuilder.withDb(db).account(a1).amount(2000).create(); TransactionBuilder.withDb(db).account(a2).amount(-100).create(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); breakRunningBalanceForAccount(a1); assertEquals(IntegrityCheck.Level.ERROR, integrity.check().level); db.rebuildRunningBalanceForAccount(a1); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); breakRunningBalance(); assertEquals(IntegrityCheck.Level.ERROR, integrity.check().level); db.rebuildRunningBalances(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); }
### Question: CurrencySelector { public void addSelectedCurrency(int selectedCurrency) { if (selectedCurrency > 0 && selectedCurrency <= currencies.size()) { List<String> c = currencies.get(selectedCurrency-1); addSelectedCurrency(c); } else { listener.onCreated(0); } } CurrencySelector(Context context, MyEntityManager em, OnCurrencyCreatedListener listener); void show(); void addSelectedCurrency(int selectedCurrency); }### Answer: @Test public void should_add_selected_currency_as_default_if_it_is_the_very_first_currency_added() { givenNoCurrenciesYetExist(); selector.addSelectedCurrency(1); Currency currency1 = db.load(Currency.class, currencyId); assertTrue(currency1.isDefault); selector.addSelectedCurrency(2); Currency currency2 = db.load(Currency.class, currencyId); assertTrue(currency1.isDefault); assertFalse(currency2.isDefault); }
### Question: CategoryCache { public static String extractCategoryName(String name) { int i = name.indexOf('/'); if (i != -1) { name = name.substring(0, i); } return name; } static String extractCategoryName(String name); void loadExistingCategories(DatabaseAdapter db); void insertCategories(DatabaseAdapter dbAdapter, Set<? extends CategoryInfo> categories); Category findCategory(String category); public Map<String, Category> categoryNameToCategory; public CategoryTree<Category> categoryTree; }### Answer: @Test public void should_split_category_name() { assertEquals("P1", extractCategoryName("P1")); assertEquals("P1:c1", extractCategoryName("P1:c1")); assertEquals("P1", extractCategoryName("P1/C2")); assertEquals("P1:c1", extractCategoryName("P1:c1/C2")); }
### Question: Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); }### Answer: @Test public void should_pay_1_when_buy_espresso() { Espresso espresso = new Espresso(false, false); assertTrue(espresso.cost() == 4.0); } @Test public void should_pay_5_when_buy_espresso_with_milk() { Espresso espresso = new Espresso(true, false); assertTrue(espresso.cost() == 5.0); } @Test public void should_pay_7_when_buy_espresso_with_mocha() { Espresso espresso = new Espresso(false, true); assertTrue(espresso.cost() == 7.0); } @Test public void should_pay_8_when_buy_espresso_with_milk_and_mocha() { Espresso espresso = new Espresso(true, true); assertTrue(espresso.cost() == 8.0); }
### Question: RemoteControl { public void off(int slot) { if (slot == 1) light.off(); if (slot == 2) ceiling.off(); if (slot == 3) stereo.off(); } RemoteControl(Light light, Ceiling ceiling, Stereo stereo); void on(int slot); void off(int slot); }### Answer: @Test public void should_turn_off_stereo_when_press_third_off_button() { Stereo stereo = new Stereo(); RemoteControl remoteControl = new RemoteControl(null, null, stereo); remoteControl.off(3); assertFalse(stereo.getCdStatus()); assertFalse(stereo.getCdStatus()); assertEquals(0, stereo.getVolume()); } @Test public void should_turn_off_light_when_press_first_off_button() { Light light = new Light(); RemoteControl remoteControl = new RemoteControl(light, null, null); remoteControl.off(1); assertFalse(light.status()); } @Test public void should_turn_off_ceiling_when_press_second_off_button() { Ceiling ceiling = new Ceiling(); RemoteControl remoteControl = new RemoteControl(null, ceiling, null); remoteControl.off(2); assertEquals(CeilingSpeed.Off, ceiling.getSpeed()); }
### Question: GumballMachine { public MachineStatus getState() { return State; } GumballMachine(int gumballNum, MachineStatus machineStatus); int getGumballNum(); void setGumballNum(int gumballNum); MachineStatus getState(); void setState(MachineStatus state); String insertQuarter(); String turnCrank(); String dispense(); String ejectQuarter(); final String insertedQuarterMessage; }### Answer: @Test public void gumball_machine_status_should_be_no_quarter_at_start() { GumballMachine gumballMachine = new GumballMachine(10, MachineStatus.NO_QUARTER); assertEquals(MachineStatus.NO_QUARTER, gumballMachine.getState()); }
### Question: WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } WeatherData(SeedingMachine seedingMachine, ReapingMachine reapingMachine, WateringMachine wateringMachine); void measurementsChanged(int temp, int humidity, int windPower); }### Answer: @Test public void seeding_machine_should_start_if_temperature_over_5_degree() { weatherData.measurementsChanged(10, 0, 0); assertTrue(seedingMachine.getStatus()); } @Test public void reaping_machine_should_start_if_temperature_over_5_degree_and_humidity_over_65() { weatherData.measurementsChanged(10, 70, 0); assertTrue(reapingMachine.getStatus()); } @Test public void water_machine_should_start_if_temperature_over_10_degree_and_humidity_less_than_55_and_wind_power_less_than_4() { weatherData.measurementsChanged(12, 50, 2); assertTrue(wateringMachine.getStatus()); }
### Question: MenuItem { public List<Integer> getHealthRating() { return ingredients.stream() .map(Ingredient::getHealthRating) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); }### Answer: @Test public void should_calc_health_rating_Ingredient() { assertEquals(1, flour.getHealthRating()); } @Test public void should_calc_health_rating_for_MenuItem() { assertEquals(2, moonCake.getHealthRating().size()); assertTrue(moonCake.getHealthRating().contains(1)); assertTrue(moonCake.getHealthRating().contains(2)); }
### Question: MenuItem { public List<String> getProtein() { return ingredients.stream() .map(Ingredient::getProtein) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); }### Answer: @Test public void should_calc_protein_for_Ingredient() { assertEquals("100.0 g", flour.getProtein()); } @Test public void should_calc_protein_for_MenuItem() { assertEquals(2, moonCake.getProtein().size()); assertTrue(moonCake.getProtein().contains("100.0 g")); assertTrue(moonCake.getProtein().contains("200.0 g")); }
### Question: MenuItem { public List<String> getCalory() { List<String> calories = ingredients.stream() .map(Ingredient::getCalory) .collect(Collectors.toList()); calories.add("Cooking will double calories!!!"); return calories; } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); }### Answer: @Test public void should_calc_calory_for_Ingredient() { assertEquals("10 J", flour.getCalory()); } @Test public void should_calc_calory_for_MenuItem() { assertEquals(3, moonCake.getCalory().size()); assertTrue(moonCake.getCalory().contains("10 J")); assertTrue(moonCake.getCalory().contains("20 J")); assertTrue(moonCake.getCalory().contains("Cooking will double calories!!!")); }
### Question: UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } String checkSecurity(List<String> people); }### Answer: @Test public void should_get_alert_message_if_people_names_include_don() { List<String> peopleNames = Arrays.asList("Don", "Kent"); UsingReturn usingReturn = new UsingReturn(); String alertMessage = usingReturn.checkSecurity(peopleNames); assertEquals("AlertDon", alertMessage); } @Test public void should_get_alert_message_if_people_names_include_john() { List<String> peopleNames = Arrays.asList("John", "Kent"); UsingReturn usingReturn = new UsingReturn(); String alertMessage = usingReturn.checkSecurity(peopleNames); assertEquals("AlertJohn", alertMessage); } @Test public void should_alert_first_matched_people() { List<String> peopleNames = Arrays.asList("John", "Don"); UsingReturn usingReturn = new UsingReturn(); String alertMessage = usingReturn.checkSecurity(peopleNames); assertEquals("AlertJohn", alertMessage); } @Test public void should_not_get_alert_message_if_people_names_does_include_don_and_john() { List<String> peopleNames = Arrays.asList("Martin", "Kent"); UsingReturn usingReturn = new UsingReturn(); String alertMessage = usingReturn.checkSecurity(peopleNames); assertEquals("", alertMessage); }
### Question: OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); double disabilityAmount(); }### Answer: @Test public void should_get_zero_disability_amount_given_seniority_less_than_two() { OrsExample consolidateConditionalExpression = new OrsExample(1, 0, false); assertEquals(0, consolidateConditionalExpression.disabilityAmount(), 0); } @Test public void should_get_zero_disability_amount_given_month_disabled_more_than_12() { OrsExample consolidateConditionalExpression = new OrsExample(2, 13, false); assertEquals(0, consolidateConditionalExpression.disabilityAmount(), 0); } @Test public void should_get_zero_disability_amount_given_is_part_time() { OrsExample consolidateConditionalExpression = new OrsExample(2, 1, true); assertEquals(0, consolidateConditionalExpression.disabilityAmount(), 0); } @Test public void should_get_ten_disability_amount_given_seniority_greater_than_one_and_disabled_less_than_13_and_is_not_part_time() { OrsExample consolidateConditionalExpression = new OrsExample(2, 1, false); assertEquals(10, consolidateConditionalExpression.disabilityAmount(), 0); }
### Question: AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } AndsExample(double lengthOfService, boolean onVacation); double getCharge(); }### Answer: @Test public void should_get_1_given_is_on_vacation_and_length_of_service_greater_than_10() { AndsExample andsExample = new AndsExample(11, true); assertEquals(1, andsExample.getCharge(), 0); } @Test public void should_get_point_5_given_is_not_on_vacation() { AndsExample andsExample = new AndsExample(11, false); assertEquals(0.5, andsExample.getCharge(), 0); } @Test public void should_get_point_5_given_length_of_service_not_greater_than_10() { AndsExample andsExample = new AndsExample(5, true); assertEquals(0.5, andsExample.getCharge(), 0); }
### Question: ConsolidateDuplicateConditionalFragments { public double disabilityAmount() { if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } return total; } ConsolidateDuplicateConditionalFragments(boolean isSpecialDeal, double price); double disabilityAmount(); }### Answer: @Test public void should_get_disability_amount_given_is_special_deal() { ConsolidateDuplicateConditionalFragments consolidateDuplicateConditionalFragments = new ConsolidateDuplicateConditionalFragments(true, 10); assertEquals(10.5, consolidateDuplicateConditionalFragments.disabilityAmount(), 0); } @Test public void should_get_zero_disability_amount_given_month_disabled_more_than_12() { ConsolidateDuplicateConditionalFragments consolidateDuplicateConditionalFragments = new ConsolidateDuplicateConditionalFragments(false, 10); assertEquals(10.8, consolidateDuplicateConditionalFragments.disabilityAmount(), 0); }
### Question: ChargeCalculator { public double getCharge(Date date, double quantity) { double charge; if (date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * winterRate + winterServiceCharge; else charge = quantity * summerRate; return charge; } double getCharge(Date date, double quantity); }### Answer: @Test public void should_get_summer_charge_given_date_is_in_summer() { ChargeCalculator chargeCalculator = new ChargeCalculator(); double charge = chargeCalculator.getCharge(new Date(2011, 7, 1), 100); assertEquals(200, charge, 0); } @Test public void should_get_winter_charge_given_date_is_not_in_summer() { ChargeCalculator chargeCalculator = new ChargeCalculator(); double charge = chargeCalculator.getCharge(new Date(2011, 11, 1), 100); assertEquals(400, charge, 0); }
### Question: Client { public String getStatement() { String plan = customer() == null ? "Basic Plan" : customer().getPlan(); String customerName = customer() == null ? "occupant" : customer().getName(); int weeksDelinquent = customer() == null ? 0 : customer().getWeeksDelinquentInLastYear(); return plan + " " + customerName + " " + weeksDelinquent; } Client(Site site); String getStatement(); }### Answer: @Test public void should_get_basic_statement_given_does_not_have_customer() { Site site = new Site(null); Client client = new Client(site); assertEquals("Basic Plan occupant 0", client.getStatement()); } @Test public void should_get_customer_statement_given_has_customer() { Site site = new Site(new Customer()); Client client = new Client(site); assertEquals("Real Plan Name 100", client.getStatement()); }
### Question: Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } Employee(int type); int payAmount(); }### Answer: @Test public void should_get_pay_amount_for_engineer_given_type_is_engineer() throws Exception { Employee employee = new Employee(EmployeeType.ENGINEER); assertEquals(100, employee.payAmount()); } @Test public void should_get_pay_amount_for_sales_man_given_type_is_sales_man() throws Exception { Employee employee = new Employee(EmployeeType.SALESMAN); assertEquals(120, employee.payAmount()); } @Test public void should_get_pay_amount_for_manager_given_type_is_manager() throws Exception { Employee employee = new Employee(EmployeeType.MANAGER); assertEquals(150, employee.payAmount()); }
### Question: ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); double getPayAmount(); }### Answer: @Test public void should_get_dead_amount_pay_given_is_dead() { ReplaceNestedConditionalWithGuardClauses replaceNestedConditionalWithGuardClauses = new ReplaceNestedConditionalWithGuardClauses(true, false, false); assertEquals(400, replaceNestedConditionalWithGuardClauses.getPayAmount(), 0); } @Test public void should_get_separated_amount_pay_given_is_separated_and_not_dead() { ReplaceNestedConditionalWithGuardClauses replaceNestedConditionalWithGuardClauses = new ReplaceNestedConditionalWithGuardClauses(false, true, false); assertEquals(300, replaceNestedConditionalWithGuardClauses.getPayAmount(), 0); } @Test public void should_get_separated_amount_pay_given_is_retired_and_not_dead_and_not_seperated() { ReplaceNestedConditionalWithGuardClauses replaceNestedConditionalWithGuardClauses = new ReplaceNestedConditionalWithGuardClauses(false, false, true); assertEquals(200, replaceNestedConditionalWithGuardClauses.getPayAmount(), 0); } @Test public void should_get_normal_amount_pay_given_is_not_retired_and_not_dead_and_not_seperated() { ReplaceNestedConditionalWithGuardClauses replaceNestedConditionalWithGuardClauses = new ReplaceNestedConditionalWithGuardClauses(false, false, false); assertEquals(100, replaceNestedConditionalWithGuardClauses.getPayAmount(), 0); }
### Question: ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); double getAdjustedCapital(); }### Answer: @Test public void should_get_zero_adjusted_capital_given_capital_is_less_than_zero() { ReversingTheConditions reversingTheConditions = new ReversingTheConditions(-1, 10, 10, 10); assertEquals(0, reversingTheConditions.getAdjustedCapital(), 0); } @Test public void should_get_zero_adjusted_capital_given_init_rate_is_less_than_zero() { ReversingTheConditions reversingTheConditions = new ReversingTheConditions(10, -1, 10, 10); assertEquals(0, reversingTheConditions.getAdjustedCapital(), 0); } @Test public void should_get_zero_adjusted_capital_given_duration_is_less_than_zero() { ReversingTheConditions reversingTheConditions = new ReversingTheConditions(10, 10, -1, 10); assertEquals(0, reversingTheConditions.getAdjustedCapital(), 0); } @Test public void should_get_adjusted_capital_given_duration_and_capital_and_init_rate_all_are_greater_than_zero() { ReversingTheConditions reversingTheConditions = new ReversingTheConditions(10, 10, 5, 10); assertEquals(4, reversingTheConditions.getAdjustedCapital(), 0); }
### Question: InlineTemp { public boolean isAmountOver1000() { double amount = order.getAmount(); return amount > 1000; } InlineTemp(int amount); boolean isAmountOver1000(); }### Answer: @Test public void should_get_true_given_amount_over_1000() { InlineTemp inlineTemp = new InlineTemp(2000); assertTrue(inlineTemp.isAmountOver1000()); } @Test public void should_get_false_given_amount_less_than_1000() { InlineTemp inlineTemp = new InlineTemp(500); assertFalse(inlineTemp.isAmountOver1000()); }
### Question: Beverage { public String getDescription() { return ""; } protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); }### Answer: @Test public void should_return_espresso_when_get_espresso_description() { Espresso espresso = new Espresso(false, false); assertTrue(Objects.equals(espresso.getDescription(), "Espresso")); }
### Question: InlineMethod { public int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } InlineMethod(double numberOfLateDeliveries); int getRating(); }### Answer: @Test public void should_get_rating_2_given_more_than_five_late_deliveries() { final int numberOfLateDeliveries = 6; InlineMethod inlineMethod = new InlineMethod(numberOfLateDeliveries); assertEquals(2, inlineMethod.getRating()); } @Test public void should_get_rating_1_given_less_than_five_late_deliveries() { final int numberOfLateDeliveries = 4; InlineMethod inlineMethod = new InlineMethod(numberOfLateDeliveries); assertEquals(1, inlineMethod.getRating()); }
### Question: ExtractMethod { public String printOwning(String name, int previousAmount) { String customerOwns = ""; double outstanding = 10 + previousAmount; customerOwns += "****/n"; customerOwns += "**Customer Owns**/n"; customerOwns += "****/n"; for (Order order : orders) { outstanding += order.getAmount(); } customerOwns += "name:" + name + "/n"; customerOwns += "amount:" + outstanding; return customerOwns; } ExtractMethod(List<Order> orders); String printOwning(String name, int previousAmount); }### Answer: @Test public void should_get_right_customer_owns() { String expectedCustomerOwns = "****/n**Customer Owns**/n****/nname:ExtractMethod/namount:140.0"; List<Order> orders = Arrays.asList(new Order(10), new Order(20)); ExtractMethod extractMethod = new ExtractMethod(orders); String owns = extractMethod.printOwning("ExtractMethod", 100); assertEquals(expectedCustomerOwns, owns); }
### Question: RemoveAssignmentsToParameters { public int discount(int inputVal, int quantity, int yearToDate) { if (inputVal > 50) inputVal -= 2; if (quantity > 100) inputVal -= 1; if (yearToDate > 10000) inputVal -= 4; return inputVal; } int discount(int inputVal, int quantity, int yearToDate); }### Answer: @Test public void should_get_discount_7_given_value_is_over_50_and_quantity_is_over_100_and_yearToEnd_is_over_10000() { RemoveAssignmentsToParameters removeAssignmentsToParameters = new RemoveAssignmentsToParameters(); assertEquals(53, removeAssignmentsToParameters.discount(60, 200, 20000)); } @Test public void should_get_discount_5_given_value_is_less_than_50_and_quantity_is_over_100_and_yearToEnd_is_over_10000() { RemoveAssignmentsToParameters removeAssignmentsToParameters = new RemoveAssignmentsToParameters(); assertEquals(35, removeAssignmentsToParameters.discount(40, 200, 20000)); }
### Question: ReplaceTempWithQuery { public double getPrice() { double basePrice = quantity * itemPrice; double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice * discountFactor; } ReplaceTempWithQuery(double quantity, double itemPrice); double getPrice(); }### Answer: @Test public void should_get_right_discount_given_base_price_is_over_1000() { ReplaceTempWithQuery replaceTempWithQuery = new ReplaceTempWithQuery(1000, 2); assertEquals(1900, replaceTempWithQuery.getPrice(), 2); } @Test public void should_get_right_discount_given_base_price_is_less_than_1000() { ReplaceTempWithQuery replaceTempWithQuery = new ReplaceTempWithQuery(400, 2); assertEquals(784, replaceTempWithQuery.getPrice(), 2); }
### Question: ReplaceMethodWithMethodObject { public int gamma(int inputVal, int quantity, int yearToDate) { int importantValue1 = inputVal * quantity; int importantValue2 = inputVal * yearToDate + 100; if ((yearToDate - importantValue1) > 100) importantValue2 -= 20; int importantValue3 = importantValue2 * 7; return importantValue3 - 2 * importantValue1; } int gamma(int inputVal, int quantity, int yearToDate); }### Answer: @Test public void should_get_right_gamma_given() { ReplaceMethodWithMethodObject replaceMethodWithMethodObject = new ReplaceMethodWithMethodObject(); int gamma = replaceMethodWithMethodObject.gamma(10, 5, 100); assertEquals(7600, gamma); }
### Question: SeparateQueryFromModifier { public String checkSecurity(String[] people) { String found = foundMiscreant(people); return someLaterCode(found); } String checkSecurity(String[] people); }### Answer: @Test public void should_get_alert_message_if_people_names_include_don() { String[] peopleNames = new String[]{"Don", "Kent"}; SeparateQueryFromModifier separateQueryFromModifier = new SeparateQueryFromModifier(); String alertMessage = separateQueryFromModifier.checkSecurity(peopleNames); assertEquals("AlertDon", alertMessage); } @Test public void should_get_alert_message_if_people_names_include_john() { String[] peopleNames = new String[]{"John", "Kent"}; SeparateQueryFromModifier separateQueryFromModifier = new SeparateQueryFromModifier(); String alertMessage = separateQueryFromModifier.checkSecurity(peopleNames); assertEquals("AlertJohn", alertMessage); } @Test public void should_not_get_alert_message_if_people_names_does_include_don_and_john() { String[] peopleNames = new String[]{"Martin", "Kent"}; SeparateQueryFromModifier separateQueryFromModifier = new SeparateQueryFromModifier(); String alertMessage = separateQueryFromModifier.checkSecurity(peopleNames); assertEquals("null", alertMessage); }
### Question: RemoteControl { public void on(int slot) { if (slot == 1) light.on(); if (slot == 2) ceiling.high(); if (slot == 3) { stereo.on(); stereo.setCdStatus(true); stereo.setVolume(11); } } RemoteControl(Light light, Ceiling ceiling, Stereo stereo); void on(int slot); void off(int slot); }### Answer: @Test public void should_turn_on_light_when_press_first_on_button() { Light light = new Light(); RemoteControl remoteControl = new RemoteControl(light, null, null); remoteControl.on(1); assertTrue(light.status()); } @Test public void should_turn_on_ceiling_when_press_second_on_button() { Ceiling ceiling = new Ceiling(); RemoteControl remoteControl = new RemoteControl(null, ceiling, null); remoteControl.on(2); assertEquals(CeilingSpeed.High, ceiling.getSpeed()); } @Test public void should_turn_on_stereo_when_press_third_on_button() { Stereo stereo = new Stereo(); RemoteControl remoteControl = new RemoteControl(null, null, stereo); remoteControl.on(3); assertTrue(stereo.getStereoStatus()); assertTrue(stereo.getCdStatus()); assertEquals(11, stereo.getVolume()); }
### Question: HideMethod { public String getLastReadingName() { List<String> readings = Arrays.asList("Refactoring", "Clean Code"); return getLast(readings); } String getLastReadingName(); String getLast(List<String > readings); }### Answer: @Test public void should_get_last_reading_name() { HideMethod hideMethod = new HideMethod(); assertEquals("Clean Code", hideMethod.getLastReadingName()); }
### Question: DateCalculator { public Date getDate() { return new Date(previousDate.getYear(), previousDate.getMonth(), previousDate.getDate() + 1); } DateCalculator(Date previousDate); Date getDate(); }### Answer: @Test public void should_get_correct_next_day() { Date previousDate = new Date(2011, 10, 11); DateCalculator calculateDate = new DateCalculator(previousDate); Date nextDay = new Date(2011, 10, 12); assertEquals(nextDay, calculateDate.getDate()); }
### Question: DateManager { public Date getDate() { return new Date(previousDate.getYear(), previousDate.getMonth(), previousDate.getDate() + 1); } DateManager(Date previousDate); Date getDate(); }### Answer: @Test public void should_get_correct_next_day() { Date previousDate = new Date(2011, 11, 11); DateManager calculateDate = new DateManager(previousDate); Date nextDay = new Date(2011, 11, 12); assertEquals(nextDay, calculateDate.getDate()); }
### Question: PersonForExtractClass { public String getTelephoneNumber() { return ("(" + officeAreaCode + ") ") + officeNumber; } PersonForExtractClass(String officeAreaCode, String officeNumber); String getTelephoneNumber(); String getName(); void setName(String name); }### Answer: @Test public void should_get_correct_telephone_number() { PersonForExtractClass personForExtractClass = new PersonForExtractClass("CA", "01"); assertEquals("(CA) 01", personForExtractClass.getTelephoneNumber()); }
### Question: IntRange { public boolean includes(int arg) { return arg >= low && arg <= high; } IntRange(int low, int high); boolean includes(int arg); void grow(int factor); }### Answer: @Test public void should_not_include_when_number_is_less_than_low_and_greater_than_high() { IntRange intRange = new IntRange(50, 100); assertFalse(intRange.includes(150)); } @Test public void should_include_when_number_is_between_low_and_high() { IntRange intRange = new IntRange(50, 100); assertTrue(intRange.includes(80)); }
### Question: Customer { public String getCustomerName() { return customerName; } Customer(String customerName); String getCustomerName(); }### Answer: @Test public void should_get_number_of_orders_for_customer() { Order kentOrder1 = new Order("Kent"); Order kentOrder2 = new Order("Kent"); assertEquals("Kent", kentOrder1.getCustomer().getCustomerName()); assertEquals("Kent", kentOrder2.getCustomer().getCustomerName()); }
### Question: Currency { public String getCode() { return code; } Currency(String code); String getCode(); }### Answer: @Test public void should_two_currencies_with_the_same_unit_are_equal() { Currency usdCurrency1 = new Currency("USD"); Currency usdCurrency2 = new Currency("USD"); assertEquals(usdCurrency1.getCode(), usdCurrency2.getCode()); }
### Question: EnergyCalculator { public double potentialEnergy(double mass, double height) { return mass * height * 9.81; } double potentialEnergy(double mass, double height); }### Answer: @Test public void should_get_potential_energy() { EnergyCalculator energyCalculator = new EnergyCalculator(); double potentialEnergy = energyCalculator.potentialEnergy(10, 10); assertTrue(potentialEnergy == 981); }
### Question: LifelineSite { public Dollars charge() { int usage = readings[0].getAmount() - readings[1].getAmount(); return charge(usage); } void addReading(Reading newReading); Dollars charge(); }### Answer: @Test(expected = NullPointerException.class) public void should_throw_exception_given_no_reading() { LifelineSite subject = new LifelineSite(); subject.charge(); }
### Question: BusinessSite { public Dollars charge() { int usage = readings[lastReading].getAmount() - readings[lastReading - 1].getAmount(); return charge(usage); } void addReading(Reading newReading); Dollars charge(); }### Answer: @Test(expected = NullPointerException.class) public void should_throw_exception_given_no_reading() { BusinessSite subject = new BusinessSite(); subject.charge(); }