- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想对这段代码进行单元测试,以验证调用了哪个 DriverManager.getConnection() 。DriverManager.getConnection(url,user,pass) 或 DriverManager.getConnection(url) 根据条件。
我找不到任何 Gradle 示例作为测试此功能的引用。
static void testDbConnectivity(HashMap<DbConfigParam, String> options) {
DatabaseVendor dbVendor = Enum.valueOf(DatabaseVendor.class, options.get(DbConfigParam.dbVendor));
String host = options.get(DbConfigParam.host);
String port = options.get(DbConfigParam.port);
String db = options.get(DbConfigParam.db);
String user = options.get(DbConfigParam.user);
String pass = options.get(DbConfigParam.password);
String url = String.format(dbVendor.getUrlFormat(), host, Integer.valueOf(port), db);
System.out.format("Database URL: %s %n", url);
try {
Class.forName(dbVendor.getDriverClass());
} catch (Exception e) {
throw new IllegalStateException(String.format("Error checking database connectivity.%n %s", Utils.getStacktrace(e)));
}
try {
Connection connection = null;
if(dbVendor.getVendorName().equalsIgnoreCase("mssql") && Utils.containsIgnoreCase(url,"Authentication=ActiveDirectoryMsi")){
connection = DriverManager.getConnection(url);
}else {
connection = DriverManager.getConnection(url, user, pass);
}
System.out.format("Connection Established. Database Version: %s %n",
connection.getMetaData().getDatabaseProductVersion());
} catch (Exception e) {
throw new IllegalStateException(String.format("Error checking database connectivity.%n %s", e.getMessage()));
}
}
这是我正在编写的测试用例
package com.acl.db;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import static org.mockito.Mockito.*;
@RunWith(PowerMockRunner.class)
public class DbConnectionValidatorTest {
@Before
public void setup() throws SQLException {
}
@After
public void tearDown(){
}
@Test
public void testTestDbConnectivityWithMSI()throws Exception {
Connection connection = mock(Connection.class);
PowerMockito.mockStatic(DriverManager.class);
PowerMockito.when(DriverManager.class, "getConnection", anyString(), anyString(), anyString()).thenReturn(connection);
// when(driverManager.getConnection(anyString()));
HashMap<DbConfigParam, String> options = new HashMap<>();
options.put(DbConfigParam.host,"");
options.put(DbConfigParam.port,"");
options.put(DbConfigParam.db,"");
options.put(DbConfigParam.user,"");
options.put(DbConfigParam.password,"");
DbConnectionValidator dbConnectionValidator = new DbConnectionValidator();
dbConnectionValidator.testDbConnectivity(options);
// verify()
}
}
抛出错误,例如
Testing started at 4:56 PM ...
> Task :keycloak-acl:utils:datasource-updater:cleanTest
> Task :keycloak-acl:utils:datasource-updater:compileJava UP-TO-DATE
> Task :keycloak-acl:utils:datasource-updater:processResources NO-SOURCE
> Task :keycloak-acl:utils:datasource-updater:classes UP-TO-DATE
> Task :keycloak-acl:utils:datasource-updater:compileTestJava
> Task :keycloak-acl:utils:datasource-updater:processTestResources NO-SOURCE
> Task :keycloak-acl:utils:datasource-updater:testClasses
> Task :keycloak-acl:utils:datasource-updater:test FAILED
No suitable driver found for
java.sql.SQLException: No suitable driver found for
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1873)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:773)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:753)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:466)
at org.powermock.api.mockito.PowerMockito.when(PowerMockito.java:473)
at com.ca.devtest.acl.db.DbConnectionValidatorTest.testTestDbConnectivityWithMSI(DbConnectionValidatorTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:175)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:157)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)
com.ca.devtest.acl.db.DbConnectionValidatorTest > testTestDbConnectivityWithMSI FAILED
java.sql.SQLException at DbConnectionValidatorTest.java:40
1 test completed, 1 failed
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':keycloak-acl:utils:datasource-updater:test'.
> There were failing tests. See the report at: file:///Users/ajay/driveD/project/10.6/keycloak/keycloak-acl/utils/datasource-updater/build/reports/tests/test/index.html
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.2.1/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 1s
4 actionable tasks: 3 executed, 1 up-to-date
最佳答案
我已经解决了我的问题,能够使用以下代码进行单元测试。
build.gradle
dependencies {
testImplementation 'junit:junit:4.12'
testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '1.6.4'
testCompile group: 'org.powermock', name: 'powermock-api-mockito', version: '1.6.4'
compile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '8.2.1.jre8'
}
DbConnectionValidatorTest
package com.acl.db;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;
@RunWith(PowerMockRunner.class)
@PrepareForTest({DbConnectionValidator.class})
public class DbConnectionValidatorTest {
@Test
public void testTestDbConnectivityWithMSI()throws Exception {
Connection conn = mock(Connection.class);
mockStatic(DriverManager.class);
mockStatic(DatabaseMetaData.class);
when(DriverManager.getConnection(anyString())).thenReturn(conn);
when(conn.getMetaData().getDatabaseProductVersion()).thenReturn("TestSuccessWithMSI");
HashMap<DbConfigParam, String> options = new HashMap<>();
options.put(DbConfigParam.dbVendor,"MSSQL");
options.put(DbConfigParam.host,"localhost");
options.put(DbConfigParam.port,"1433");
options.put(DbConfigParam.db,"database=keycloakdb;Authentication=ActiveDirectoryMsi;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
DbConnectionValidator dbConnectionValidator = new DbConnectionValidator();
dbConnectionValidator.testDbConnectivity(options);
verifyStatic();
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=database=keycloakdb;Authentication=ActiveDirectoryMsi;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
}
@Test
public void testTestDbConnectivityNonMSI()throws Exception {
Connection conn = mock(Connection.class);
mockStatic(DriverManager.class);
mockStatic(DatabaseMetaData.class);
when(DriverManager.getConnection(anyString(),anyString(),anyString())).thenReturn(conn);
when(conn.getMetaData().getDatabaseProductVersion()).thenReturn("TESTSuccessWithNoMSI");
HashMap<DbConfigParam, String> options = new HashMap<>();
options.put(DbConfigParam.dbVendor,"MSSQL");
options.put(DbConfigParam.host,"localhost");
options.put(DbConfigParam.port,"1433");
options.put(DbConfigParam.db,"mssqldb");
options.put(DbConfigParam.user,"test");
options.put(DbConfigParam.password,"testpwd");
DbConnectionValidator dbConnectionValidator = new DbConnectionValidator();
dbConnectionValidator.testDbConnectivity(options);
verifyStatic();
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=mssqldb","test","testpwd");
}
}
我能够使用上述实现进行单元测试。
关于java - 如何使用 Powermock、easymock、mockito 进行单元测试 DriverManager.getConnection ("") 或 DriverManager.getConnection ("","","") 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60720973/
我想更好地理解 EasyMock,并使用它我想出了这个问题。 我想做的是对一个对象设置一个负期望,以检查在测试期间是否没有调用某个方法(在验证那些初始期望时)。 我知道 verify 的默认行为是检查
有没有一种简单的方法来模拟这个调用: objectA.getB().getC(); 现在我这样做的方式是: A mockA = EasyMock.createMock(A.class); B mock
我试图模拟对 final方法的调用 ResourceBundle.getString() .使用 PowerMock 1.4.12 和 EasyMock 3.1,调用不会被模拟;而是调用“真实”方法。
我正在使用 EasyMock 和 EasyMock CE 3.0 来模拟依赖层并测试我的类。以下是我无法找到任何解决方案的场景 我有一个要测试的类,它调用一个依赖类void 方法,该方法接受输入参数,
我有一个间接使用类 Foo 的测试用例。为了测试用例的目的,我不在乎 Foo 是什么。我应该能够 mock 它。 Foo mock = EasyMock.createMock(Foo.class);
我已经使用 EasyMock 编写了很多 Mock 对象。然而,我经常发现编写部分模拟非常耗时,而且感觉不“正确”。 我会说这是一个设计错误,因为我尝试模拟的类将多个关注点合二为一,因此我应该创建单独
在我的单元测试中,我使用 EasyMock 创建模拟对象。在我的测试代码中我有这样的东西 EasyMock.expect(mockObject.someMethod(anyObject())).and
所以我已经使用 EasyMock 的类扩展有一段时间了。突然间,我遇到了这个异常,但只有当我运行整个测试套件时: java.lang.IllegalStateException: 0 matchers
这有什么区别: ResultSet set = EasyMock.createNiceMock(ResultSet.class); EasyMock.expect(set.getInt("col1")
我正在尝试完成有关 easymock 的教程以首次使用它。 http://www.vogella.de/articles/EasyMock/article.html 我正在使用- 面向 Java 开发
我正在使用 TestNG、EasyMock 和 PowerMock 进行测试。根据下面的代码,我尝试模拟从被测静态方法(fetchAuthenticator)调用的静态方法。当我运行测试时,execu
我被分配了将我们的模拟代码从 EasyMock 1-style 升级到 EasyMock 2/3-style 的任务(现在是时候了,因为 EasyMock 1 的大部分内容已于 2005 年被弃用并于
在 API 文档中提到在 strictmock 中默认启用顺序检查,而在 nice mock 的情况下它不是。我不明白他们所说的“订单检查”到底是什么意思。 最佳答案 如果您告诉 mock 期望调用
根据标题,只是想知道是否有一种带有 easymock 的机制来测试方法在其生命周期内是否未被调用。 最佳答案 我知道这个问题很老,但我和 OP 有同样的问题,并做了更多的环顾四周。我找到了以下解决方案
我正在尝试在带有 EasyMock 的 JUnit 中设置测试,但遇到了一个我似乎无法解决的小问题。我希望这里有人可以提供帮助。 这是我尝试测试的方法的简化版本: public void myMeth
这是我第一次使用 EasyMock,我正在尝试向一些遗留代码添加一些单元测试。 遗留代码位于 Spring 3.1 中,我使用的是 EasyMock 3.4。 我在这里想要完成的是测试调用 dao 的
是否可以为循环调用的模拟设置不同的期望? 考虑到用例, while(condition){ List list = Database call //Call to be mocked ..
我正在使用 EasyMock 尝试通过两层深度的项目列表来模拟迭代。我的单元测试代码如下 EventContext ctx = EasyMock.createMock(EventContext
我在使用 EasyMock 时遇到一些奇怪的行为。我已经设置了一些期望,但是当我运行测试时,EasyMock 失败了,因为我的期望按指定执行。以下是失败的示例: Unexpected method c
例如,我创建一个对象,并想为其设置一个属性。问题是,该属性永远不会被设置,因为 EasyMock 会拦截它。如何解决这个问题? ctx = control.createMock(EGContext.c
我是一名优秀的程序员,十分优秀!