為使用mock方案測試,而重構代碼的小小案例
阿新 • • 發佈:2019-03-29
set pro ger config ntb tco sql style .get
import com.sun.deploy.config.DefaultConfig; import javax.security.auth.login.Configuration; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; public class Test { } interface AccountManager{ Account findAccountForUser(String userId); void updateAccount(Account account); }class LogFactory{ public static Log getLog(Class cls){return null;} } class Account { } class Log { void debug(String string){}} //原版本的代碼 class DefaultAccountManager implements AccountManager{ Log logger = LogFactory.getLog(AccountManager.class); public Account findAccountForUser(String userId) { logger.debug("hahahahahaha"); ResourceBundle bundle = PropertyResourceBundle.getBundle("test"); String sql = bundle.getString("test"); return null; } public void updateAccount(Account account) { } } //為測試進行重構的代碼 class DefaultAccountManager1 implements AccountManager{ Log logger;private Configuration configuration; public DefaultAccountManager1() { this(LogFactory.getLog(DefaultAccountManager.class),new DefaultConfiguration()) } public DefaultAccountManager1(Log logger, Configuration configuration) { this.logger = logger; this.configuration = configuration; } public Account findAccountForUser(String userId) { logger.debug("hahahahahaha"); this.configuration.getSql("test"); return null; } public void updateAccount(Account account) { } } //測試時候的代碼 class TestDefaultAccountManager{ public void testFindAccountByUser(){ MockLog logger = new MockLog(); MockConfiguration configuration = new MockConfiguration(); configuration.setSQl("testtesttest"); DefaultAccountManager am = new DefaultAccountManager(logger, configuration); Account account = am.findAccountForUser("1234"); } }
為使用mock方案測試,而重構代碼的小小案例