@SuppressWarnings("unchecked") @Test public void testDecorateUrl() { // GIVEN IMocksControl mc = EasyMock.createControl(); String url = "foo[x]bar"; Configuration conf = mc.createMock(Configuration.class); Set<Entry<String, Object>> entrySet = new HashSet<Entry<String, Object>>(); Entry<String, Object> entry = mc.createMock(Entry.class); entrySet.add(entry); ConfigurationService sut = new ConfigurationService(); // EXPECT expect(conf.entrySet()).andReturn((Set<Entry<String, Object>>) entrySet); expect(entry.getKey()).andReturn("[x]").anyTimes(); expect(entry.getValue()).andReturn("bar").anyTimes(); // WHEN mc.replay(); String result = sut.decorateUrl(url, conf); // THEN assertEquals("Expected to replace message params.", "foobarbar", result); mc.verify(); }
/** * AccountManager的单元测试用例, 测试Service层的业务逻辑. * * <p>使用EasyMock对UserDao进行模拟. * * @author calvin */ public class AccountManagerTest { private IMocksControl control = EasyMock.createControl(); private AccountManager accountManager; private UserDao mockUserDao; @Before public void setUp() { accountManager = new AccountManager(); mockUserDao = control.createMock(UserDao.class); accountManager.setUserDao(mockUserDao); } @After public void tearDown() { control.verify(); } /** * 用户认证测试. * * <p>分别测试正确的用户与正确,空,错误的密码三种情况. */ @Test public void authUser() { EasyMock.expect(mockUserDao.countUserByLoginNamePassword("admin", "admin")).andReturn(1L); EasyMock.expect(mockUserDao.countUserByLoginNamePassword("admin", "errorPasswd")).andReturn(0L); control.replay(); assertEquals(true, accountManager.authenticate("admin", "admin")); assertEquals(false, accountManager.authenticate("admin", "")); assertEquals(false, accountManager.authenticate("admin", "errorPasswd")); } }
public class UserDetailsServiceImplTest extends Assert { private IMocksControl control = EasyMock.createControl(); private UserDetailsServiceImpl userDetailsService; private AccountManager mockAccountManager; @Before public void setUp() { userDetailsService = new UserDetailsServiceImpl(); mockAccountManager = control.createMock(AccountManager.class); userDetailsService.setAccountManager(mockAccountManager); } @After public void tearDown() { control.verify(); } @Test public void loadUserExist() { // 准备数据 User user = new User(); user.setLoginName("admin"); user.setShaPassword(new ShaPasswordEncoder().encodePassword("admin", null)); Role role1 = new Role(); role1.setName("admin"); Role role2 = new Role(); role2.setName("user"); user.getRoleList().add(role1); user.getRoleList().add(role2); // 录制脚本 EasyMock.expect(mockAccountManager.findUserByLoginName("admin")).andReturn(user); control.replay(); // 执行测试 OperatorDetails operator = (OperatorDetails) userDetailsService.loadUserByUsername(user.getLoginName()); // 校验结果 assertEquals(user.getLoginName(), operator.getUsername()); assertEquals(new ShaPasswordEncoder().encodePassword("admin", null), operator.getPassword()); assertEquals(2, operator.getAuthorities().size()); assertEquals( new GrantedAuthorityImpl("ROLE_admin"), operator.getAuthorities().iterator().next()); assertNotNull(operator.getLoginTime()); } @Test(expected = UsernameNotFoundException.class) public void loadUserByWrongUserName() { // 录制脚本 EasyMock.expect(mockAccountManager.findUserByLoginName("foo")).andReturn(null); control.replay(); assertNull(userDetailsService.loadUserByUsername("foo")); } }
@Override protected void setUp() throws Exception { super.setUp(); control = EasyMock.createControl(); storageIo = control.createMock(StorageIo.class); userProvider = control.createMock(UserInfoProvider.class); yaWebStart = new YoungAndroidWebStartSupport(storageIo, userProvider); }
public void testDoEndTagMultipleWithTextCommentNotNull() throws JspException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException { TxNode root = new TxNode(); root.addValue(1); tst.setQuestionsTxNodeName("SurveyNodeName"); TxNode node = new TxNode(); node.addValue(1); node.addMsg("MULTIPLE_WITH_TEXT"); node.addMsg("Why did you decide not to subscribe to Premium Navigation?"); node.addMsg("1"); TxNode childNode = new TxNode(); childNode.addMsg("Don't need these features"); childNode.addMsg("Price is too high"); node.addChild(childNode); root.addChild(node); IMocksControl RequestControl = EasyMock.createControl(); HttpServletRequest request = RequestControl.createMock(HttpServletRequest.class); EasyMock.expect(request.getAttribute(tst.getQuestionsTxNodeName())).andReturn(root).anyTimes(); RequestControl.replay(); IMocksControl pageContextControl = EasyMock.createControl(); javax.servlet.jsp.PageContext pageContext = pageContextControl.createMock(javax.servlet.jsp.PageContext.class); EasyMock.expect(pageContext.getRequest()).andReturn(request).anyTimes(); IMocksControl JspWritersControl = EasyMock.createControl(); JspWriter jspwriter = JspWritersControl.createMock(JspWriter.class); EasyMock.expect(pageContext.getOut()).andReturn(jspwriter); pageContextControl.replay(); tst.setPageContext(pageContext); tst.setPageNumber(1); tst.setComments("This is test Comments"); tst.doEndTag(); String strActual = ((StringBuilder) getValue(tst, "outputText")).toString(); assertEquals("", strActual); }
public final class AFactoryCreationInvocationHandlerWithErrorsUnderTest { private static final String METHOD_GETBYTES = "getBytes"; private static final Object[] NO_PARAM = new Object[] {}; private final IMocksControl mockControl = EasyMock.createControl(); private InvocationHandler handler; private ClassLocator mockFilterChain; private Method method; private MethodParam mockMethodParam; @Before public void setup() throws Exception { MethodParamFactory mockMethodParamFactory = mockControl.createMock(MethodParamFactory.class); mockFilterChain = mockControl.createMock(ClassLocator.class); mockMethodParam = mockControl.createMock(MethodParam.class); method = getMethod(String.class, METHOD_GETBYTES); EasyMock.expect(mockMethodParamFactory.create(method, NO_PARAM)).andReturn(mockMethodParam); handler = new FactoryCreationInvocationHandler(mockFilterChain, mockMethodParamFactory); } @SuppressWarnings({"ThrowableInstanceNeverThrown"}) @Test public void shouldThrowAnImplementationNotFoundExceptionIfAClassCantBeLocated() throws Throwable { EasyMock.expect(mockFilterChain.filter(mockMethodParam)); EasyMock.expectLastCall().andThrow(new MatchNotFoundException()); mockControl.replay(); try { handler.invoke(null, method, NO_PARAM); fail(); } catch (ImplementationNotFoundException e) { mockControl.verify(); assertThat(e.getMessage(), equalTo("Could not find implementation for class [B")); } } @SuppressWarnings({"ThrowableInstanceNeverThrown"}) @Test(expected = IllegalStateException.class) public void shouldRethrowAllOtherExceptions() throws Throwable { EasyMock.expect(mockFilterChain.filter(mockMethodParam)); EasyMock.expectLastCall().andThrow(new IllegalStateException()); mockControl.replay(); handler.invoke(null, method, NO_PARAM); } private Method getMethod(final Class<?> clazz, final String methodName, final Class... classes) throws Exception { return clazz.getDeclaredMethod(methodName, classes); } }
@Before public void setUp() { this.control = EasyMock.createControl(); this.consumer = this.control.createMock(MessageConsumer.class); this.partitions = new ArrayList<Partition>(); for (int i = 0; i < 3; i++) { this.partitions.add(new Partition("0-" + i)); } this.browser = new MetaTopicBrowser( this.topic, this.maxSize, this.timeoutInMills, this.consumer, this.partitions); }
@Test public void testTrue() { final IMocksControl mocksControl = EasyMock.createControl(); final Issue issue = mocksControl.createMock(Issue.class); expect(issue.isSubTask()).andReturn(true); final AbstractIssueCondition condition = new IsSubTaskCondition(); mocksControl.replay(); assertTrue(condition.shouldDisplay(null, issue, null)); mocksControl.verify(); }
@Test public void testFalse() { final IMocksControl mocksControl = EasyMock.createControl(); final Issue issue = mocksControl.createMock(Issue.class); final User fred = new MockUser("fred"); expect(issue.isSubTask()).andReturn(false); final AbstractIssueCondition condition = new IsSubTaskCondition(); mocksControl.replay(); assertFalse(condition.shouldDisplay(fred, issue, null)); mocksControl.verify(); }
public void testDelete() { Hashtable params = new Hashtable(); params.put("object-class", "testGroup"); params.put("integerSetting", new Integer(4)); IMocksControl control = EasyMock.createControl(); Provisioning prov = control.createMock(Provisioning.class); prov.delete(params); control.andReturn(m_result); control.replay(); XmlRpcSettings xmlRpc = new XmlRpcSettings(prov); assertTrue(xmlRpc.delete(m_setting)); control.verify(); }
/** * @param toMock - the class or interface which should be mocked * @param mockType - the {@link MockType} * @param replay - true if the mock should be replayed, false if not * @return the mocked objecd */ public static Object createMock(Class<?> toMock, MockType mockType, boolean replay) { IMocksControl control = null; EasyMock.createNiceControl(); switch (mockType) { case NICE: control = EasyMock.createNiceControl(); break; case STRICT: control = EasyMock.createStrictControl(); break; default: control = EasyMock.createControl(); } Object mock = control.createMock(toMock); if (replay) { control.replay(); } return mock; }
public void testGet() { Hashtable result = new Hashtable(); result.put("result-code", new Integer(1)); result.put("integerSetting", new Integer(17)); result.put("stringSetting", "kuku"); Hashtable params = new Hashtable(); params.put("object-class", "testGroup"); params.put("integerSetting", new Integer(4)); params.put("stringSetting", "bongo"); IMocksControl control = EasyMock.createControl(); Provisioning prov = control.createMock(Provisioning.class); prov.get(params); control.andReturn(result); control.replay(); XmlRpcSettings xmlRpc = new XmlRpcSettings(prov); assertTrue(xmlRpc.get(m_setting)); assertEquals("kuku", m_setting.getSetting("stringSetting").getValue()); assertEquals("17", m_setting.getSetting("integerSetting").getValue()); control.verify(); }
public class NoteEquivalenceDirectiveTest extends TestCase { public final RecordingUi ui = new RecordingUi(); private final IMocksControl control = EasyMock.createControl(); private final FileSystem mockFs = control.createMock(FileSystem.class); private final SystemCommandRunner cmd = new SystemCommandRunner(ui); private final Repositories repositories = new Repositories(ImmutableSet.<RepositoryType.Factory>of(new DummyRepositoryFactory(mockFs))); private final InMemoryProjectContextFactory contextFactory = new InMemoryProjectContextFactory(null, cmd, mockFs, ui, repositories); private final Db.Factory dbFactory = new FileDb.Factory(mockFs, MoeModule.provideGson()); private final Db.Writer dbWriter = new FileDb.Writer(MoeModule.provideGson(), mockFs); NoteEquivalenceDirective d; @Override public void setUp() throws Exception { super.setUp(); contextFactory.projectConfigs.put( "moe_config.txt", "{'name': 'foo', 'repositories': {" + " 'internal': {'type': 'dummy'}, 'public': {'type': 'dummy'}" + "}}"); super.setUp(); // TODO(cgruber): Rip this out when Db.Factory is injected. Injector.INSTANCE = new Injector(mockFs, cmd, contextFactory, ui); d = new NoteEquivalenceDirective(contextFactory, dbFactory, dbWriter, ui); d.setContextFileName("moe_config.txt"); d.dbLocation = "/foo/db.txt"; } public void testPerform_invalidRepo() throws Exception { d.repo1 = "nonexistent(revision=2)"; d.repo2 = "public(revision=3)"; expect(mockFs.exists(new File("/foo/db.txt"))).andReturn(false); control.replay(); try { d.perform(); fail("NoteEquivalenceDirective didn't fail on invalid repository 'nonexistent'."); } catch (MoeProblem expected) { assertEquals( "No such repository 'nonexistent' in the config. Found: [internal, public]", expected.getMessage()); } control.verify(); } public void testPerform_newDbFile() throws Exception { d.repo1 = "internal(revision=1)"; d.repo2 = "public(revision=4)"; expect(mockFs.exists(new File("/foo/db.txt"))).andReturn(false); mockFs.write( Joiner.on('\n') .join( "{", " 'equivalences': [", " {", " 'rev1': {", " 'revId': '1',", " 'repositoryName': 'internal'", " },", " 'rev2': {", " 'revId': '4',", " 'repositoryName': 'public'", " }", " }", " ],", " 'migrations': []", "}") .replace('\'', '"'), new File("/foo/db.txt")); control.replay(); int result = d.perform(); control.verify(); assertEquals(0, result); } public void testPerform_existingDbFile_noChanges() throws Exception { d.repo1 = "internal(revision=1)"; d.repo2 = "public(revision=4)"; String dbString = Joiner.on('\n') .join( "{", " 'equivalences': [", " {", " 'rev1': {", " 'revId': '1',", " 'repositoryName': 'internal'", " },", " 'rev2': {", " 'revId': '4',", " 'repositoryName': 'public'", " }", " }", " ],", " 'migrations': []", "}") .replace('\'', '"'); expect(mockFs.exists(new File("/foo/db.txt"))).andReturn(true); expect(mockFs.fileToString(new File("/foo/db.txt"))).andReturn(dbString); mockFs.write(dbString, new File("/foo/db.txt")); control.replay(); int result = d.perform(); control.verify(); assertEquals(0, result); } public void testPerform_existingDbFile_addEquivalence() throws Exception { d.repo1 = "internal(revision=1)"; d.repo2 = "public(revision=4)"; String baseDbString = Joiner.on('\n') .join( "{", " 'equivalences': [", " {", " 'rev1': {", " 'revId': '0',", " 'repositoryName': 'internal'", " },", " 'rev2': {", " 'revId': '3',", " 'repositoryName': 'public'", " }", " }%s", // New equivalence is added here. " ],", " 'migrations': []", "}") .replace('\'', '"'); String oldDbString = String.format(baseDbString, ""); String newDbString = String.format( baseDbString, Joiner.on('\n') .join( ",", " {", " 'rev1': {", " 'revId': '1',", " 'repositoryName': 'internal'", " },", " 'rev2': {", " 'revId': '4',", " 'repositoryName': 'public'", " }", " }")) .replace('\'', '"'); expect(mockFs.exists(new File("/foo/db.txt"))).andReturn(true); expect(mockFs.fileToString(new File("/foo/db.txt"))).andReturn(oldDbString); mockFs.write(newDbString, new File("/foo/db.txt")); control.replay(); int result = d.perform(); control.verify(); assertEquals(0, result); } }
/** @author [email protected] (Daniel Bentley) */ public class UtilsTest extends TestCase { private final IMocksControl control = EasyMock.createControl(); private final FileSystem fileSystem = control.createMock(FileSystem.class); private final CommandRunner mockcmd = control.createMock(CommandRunner.class); // TODO(cgruber): Rework these when statics aren't inherent in the design. @dagger.Component(modules = {TestingModule.class, Module.class}) @Singleton interface Component { Injector context(); // TODO (b/19676630) Remove when bug is fixed. } @dagger.Module class Module { @Provides public CommandRunner commandRunner() { return mockcmd; } @Provides public FileSystem fileSystem() { return fileSystem; } } @Override public void setUp() throws Exception { super.setUp(); Injector.INSTANCE = DaggerUtilsTest_Component.builder().module(new Module()).build().context(); } public void testFilterByRegEx() throws Exception { assertEquals( ImmutableSet.of("foo", "br"), Utils.filterByRegEx(ImmutableSet.of("foo", "br", "bar", "baar"), ImmutableList.of("ba+r"))); } public void testCheckKeys() throws Exception { Utils.checkKeys(ImmutableMap.of("foo", "bar"), ImmutableSet.of("foo", "baz")); try { Utils.checkKeys(ImmutableMap.of("foo", "bar"), ImmutableSet.of("baz")); fail(); } catch (MoeProblem expected) { } Utils.checkKeys(ImmutableMap.<String, String>of(), ImmutableSet.<String>of()); try { Utils.checkKeys(ImmutableMap.<String, String>of("foo", "bar"), ImmutableSet.<String>of()); fail("Non-empty options map didn't fail on key emptiness check."); } catch (MoeProblem expected) { } } public void testMakeFilenamesRelative() throws Exception { assertEquals( ImmutableSet.of("bar", "baz/quux"), Utils.makeFilenamesRelative( ImmutableSet.of(new File("/foo/bar"), new File("/foo/baz/quux")), new File("/foo"))); try { Utils.makeFilenamesRelative(ImmutableSet.of(new File("/foo/bar")), new File("/dev/null")); fail(); } catch (MoeProblem p) { } } /** * Confirms that the expandToDirectory()-method calls the proper expand methods for known archive * types. * * @throws Exception */ public void testExpandToDirectory() throws Exception { String filePath = "/foo/bar.tar"; File file = new File(filePath); expect(fileSystem.getTemporaryDirectory(EasyMock.<String>anyObject())) .andReturn(new File("/test")); fileSystem.makeDirs(EasyMock.<File>anyObject()); EasyMock.expectLastCall().once(); expect( mockcmd.runCommand( EasyMock.<String>anyObject(), EasyMock.<List<String>>anyObject(), EasyMock.<String>anyObject())) .andReturn(null); control.replay(); // Run the .expandToDirectory method. File directory = Utils.expandToDirectory(file); assertNotNull(directory); assertEquals("/test", directory.toString()); control.verify(); } /** * Confirms that the expandToDirectory()-method will return null when handed a unsupported file * extension. * * @throws Exception */ public void testUnsupportedExpandToDirectory() throws Exception { String filePath = "/foo/bar.unsupportedArchive"; File file = new File(filePath); // Run the .expandToDirectory method. File directory = Utils.expandToDirectory(file); assertNull(directory); } public void testExpandTar() throws Exception { fileSystem.makeDirs(new File("/dummy/path/45.expanded")); expect(fileSystem.getTemporaryDirectory("expanded_tar_")) .andReturn(new File("/dummy/path/45.expanded")); expect( mockcmd.runCommand( "tar", ImmutableList.of("-xf", "/dummy/path/45.tar"), "/dummy/path/45.expanded")) .andReturn(""); control.replay(); File expanded = Utils.expandTar(new File("/dummy/path/45.tar")); assertEquals(new File("/dummy/path/45.expanded"), expanded); control.verify(); } public void testCopyDirectory() throws Exception { File srcContents = new File("/src/dummy/file"); File src = new File("/src"); File dest = new File("/dest"); fileSystem.makeDirsForFile(new File("/dest")); expect(fileSystem.isFile(src)).andReturn(false); expect(fileSystem.listFiles(src)).andReturn(new File[] {new File("/src/dummy")}); expect(fileSystem.getName(new File("/src/dummy"))).andReturn("dummy"); expect(fileSystem.isDirectory(new File("/src/dummy"))).andReturn(true); fileSystem.makeDirsForFile(new File("/dest/dummy")); expect(fileSystem.isFile(new File("/src/dummy"))).andReturn(false); expect(fileSystem.listFiles(new File("/src/dummy"))) .andReturn(new File[] {new File("/src/dummy/file")}); expect(fileSystem.getName(new File("/src/dummy/file"))).andReturn("file"); expect(fileSystem.isDirectory(new File("/src/dummy/file"))).andReturn(false); fileSystem.makeDirsForFile(new File("/dest/dummy/file")); fileSystem.copyFile(srcContents, new File("/dest/dummy/file")); control.replay(); Utils.copyDirectory(src, dest); control.verify(); } public void testMakeShellScript() throws Exception { File script = new File("/path/to/script"); fileSystem.write("#!/bin/sh -e\nmessage contents", script); fileSystem.setExecutable(script); control.replay(); Utils.makeShellScript("message contents", "/path/to/script"); control.verify(); } }
public class PreferencesFilterTest extends ServletFilterTestCase { EasyMock mock = new EasyMock(); PreferencesFilter filter = new PreferencesFilter(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); PreferencesStore prefStore; IMocksControl control = EasyMock.createControl(); @Override protected void setUp() throws Exception { super.setUp(); prefStore = control.createMock(PreferencesStore.class); wac.getBeanFactory().registerSingleton("preferencesStore", prefStore); context.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); filter.init(filterConfig); } public void testDoesNotCreateSession() throws Exception { EasyMock.expect(prefStore.getDefaultPreferences()).andReturn(new PreferencesDto()); filter(); assertNotNull(request.getAttribute(Keys.PREFERENCES)); } public void testLoadsPreferencesFromCookieIntoRequest() throws Exception { request.addCookie(new Cookie(Keys.PREFERENCES, "descending")); EasyMock.expect(prefStore.convertFromString("descending")).andReturn(new PreferencesDto()); filter(); assertNotNull(request.getAttribute(Keys.PREFERENCES)); } public void testLoadsPreferencesFromCookieIntoSessionIfPresent() throws Exception { request.addCookie(new Cookie(Keys.PREFERENCES, "descending")); request.getSession(); EasyMock.expect(prefStore.convertFromString("descending")).andReturn(new PreferencesDto()); filter(); assertNotNull(request.getSession().getAttribute(Keys.PREFERENCES)); } public void testDoesNotReloadsPreferencesFromCookieIntoSessionIfPresent() throws Exception { final PreferencesDto oldPrefs = new PreferencesDto(); request.getSession().setAttribute(Keys.PREFERENCES, oldPrefs); filter(); assertSame(oldPrefs, request.getSession().getAttribute(Keys.PREFERENCES)); } private void filter() throws ServletException, IOException { final boolean sessionExisted = request.getSession(false) != null; assertFalse(chain.doFilterCalled()); control.replay(); filter.doFilter(request, response, chain); control.verify(); assertTrue("Should call chain", chain.doFilterCalled()); if (!sessionExisted) { assertNull("Should not create session", request.getSession(false)); } } }
@Override protected IMocksControl initialValue() { return EasyMock.createControl(); }