我刚刚设置了一个测试,检查我是否能够使用Hibernate将条目插入到我的数据库中.令我疯狂的是,Hibernate实际上并没有删除这些条目,尽管它报告说它们已经消失了!
下面的测试运行成功,但是当我之后检查我的数据库时,插入的条目仍然存在!我甚至尝试使用assert检查它(是的,我有-ea作为vm参数).有没有人知道为什么不删除条目?
public class HibernateExportStatisticDaoIntegrationTest {
HibernateExportStatisticDao dao;
Transaction transaction;
@Before
public void setUp(){
assert numberOfStatisticRowsInDB() == 0;
dao = new HibernateExportStatisticDao(HibernateUtil.getSessionFactory());
}
@After
public void deleteAllEntries(){
assert numberOfStatisticRowsInDB() != 0;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
for(PersistableStatisticItem item:allStatisticItemsInDB()) {
session.delete(item);
}
session.flush();
assert numberOfStatisticRowsInDB() == 0;
}
@Test public void exportAllSavesEntriesToDatabase(){
int expectedNumberOfStatistics = 20;
dao.exportAll(StatisticItemFactory.createTestStatistics(expectedNumberOfStatistics));
assertEquals(expectedNumberOfStatistics, numberOfStatisticRowsInDB());
}
private int numberOfStatisticRowsInDB() {
return allStatisticItemsInDB().size();
}
@SuppressWarnings("unchecked")
private List<PersistableStatisticItem> allStatisticItemsInDB(){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
transaction = session.beginTransaction();
Query q …Run Code Online (Sandbox Code Playgroud) 我试图写它接受一个字符串作为一个对位计和抛出异常的方法的单元测试,如果它是畸形的(并且没有,如果它是好的).我想写一个参数化测试在几个字符串和期望的异常,其中饲料(包括是否良好形成的输入字符串没有抛出如此!).如果尝试使用@Test(expect = SomeException.class)注释,我遇到了两个问题:
expect = null是不允许的.那么我怎样才能测试抛出NO异常的预期结果(对于结构良好的输入字符串)?
期待=不可能?我还没有尝试过,但我强烈怀疑,这样的话看完这个(请你说明这是否是真的?): http://tech.groups.yahoo.com/group/junit/message/19383 这那么似乎是我发现的最佳解决方案.您如何看待它,特别是与此相比: 如何在参数化测试中测试异常?
提前感谢您的任何帮助,我期待着讨论:)
我想停止/销毁一个正在运行的JUnitCore
JUnitCore.run(Request.aClass(ClassToRun));
Run Code Online (Sandbox Code Playgroud)
就像pleaseStop()在RunNotifier上一样.
有任何想法吗?
http://junit.sourceforge.net/javadoc/org/junit/runner/package-summary.html
我正在使用struts2 junit 2.3.12插件.
java.lang.NoClassDefFoundError: javax/servlet/ServletContext
所以我包括
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
在我的POM中,之后我得到:
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/servlet/ServletException
Run Code Online (Sandbox Code Playgroud)
所以,我删除上面的依赖项并添加:
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-6.0</artifactId>
<version>1.0.0.Final</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
之后我得到了
SEVERE: [53:22.549] Dispatcher initialization failed
Run Code Online (Sandbox Code Playgroud)
以下是我的测试:
public class TestAction extends StrutsTestCase {
@Test
public void testRegister() throws Exception {
ActionProxy proxy = getActionProxy("/gotoregister");
assertNotNull(proxy);
proxy = getActionProxy("/registeraction");
UserAction action = (UserAction) proxy.getAction();
assertNotNull(action);
request.setParameter("usernameexists", "true");
request.setParameter("emailexists", "false");
request.setParameter("basicinfo.firstname", "fname");
request.setParameter("basicinfo.lastname", "lname"); …Run Code Online (Sandbox Code Playgroud) 我正在编写测试,我想通过测试方法捕获STDOUT上发送的消息.这是我的代码:
@Test
public void testAction() throws IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException,
CmdLineException, IOException {
PrintStream originalSTDOUT = System.out;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
try {
System.setOut(ps);
// Call to the method that will print text to STDOUT...
ps.flush();
String batchLog = baos.toString("UTF-8");
assertTrue("Invalid exception text !", batchLog.contains("my expected text..."));
} finally {
System.setOut(originalSTDOUT);//Restore original STDOUT
originalSTDOUT.write(baos.toByteArray());// Write back to STDOUT, even if I comment this line, outputs go to STDOUT...
ps.close();
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,batchLog虽然我仍然可以读到STDOUT的预期文本,但它总是空的. …
我的类是一个测试类,它具有以下结构:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public class MyClassTest {
public static void main(String[] args) {
System.out.println("in main");
}
@Test
public void maxTest() {
System.out.println("test");
}
}
Run Code Online (Sandbox Code Playgroud)
如果我按下右键单击main方法>运行'main',它会抛出以下异常:
java.lang.Exception: No tests found matching Method main(MyClassTest) from org.junit.internal.requests.ClassRequest@26aa12dd
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:35)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:41)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Run Code Online (Sandbox Code Playgroud)
如果我按下类名> Run'MyClassTest.main()',它可以正常打印:
in main
Run Code Online (Sandbox Code Playgroud)
如果我发表评论@RunWith(PowerMockRunner.class),在这两种情况下一切正常.
如果我使用@RunWith(MockitoJUnitRunner.class)而不是,则会出现同样的问题@RunWith(PowerMockRunner.class).
为什么会有这种差异?
细节:
如何测试方法是否无效.例如,我有一个静态方法,如果给定的字符串参数为null或为空(它用于参数验证),则抛出异常.现在我的测试看起来像这样:
@Test
public void notNullOrEmpty_doesNothingIfValueIsNotNullOrEmpty() {
Require.notNullOrEmpty(Generate.randomString());
assertTrue(true); // <- this looks very ugly
}
@Test(expected = IllegalArgumentException.class)
public void notNullOrEmpty_throwsExceptionIfValueIsNull() {
Require.notNullOrEmpty(null);
}
@Test(expected = IllegalArgumentException.class)
public void notNullOrEmpty_throwsExceptionIfValueIsEmpty() {
Require.notNullOrEmpty("");
}
Run Code Online (Sandbox Code Playgroud)
如何在没有通话的情况下让第一个测试通过assertTrue(true),有一个Assert.fail()类似的东西Assert.pass()?
编辑:添加缺少(expected = IllegalArgumentException.class)第3测试
使用Powermockito和Mockito为连接池构建一些简单的单元测试时遇到以下错误,我将其包裹在Hikari CP中.测试的设置如下.令我感到困惑的是,我有一些未显示的单元测试,它们都使用相同的设置和方法.只是这一个单元测试继续失败并出现该错误.无论when我把什么陈述放在顶部,他们都找不到方法.
org.powermock.reflect.exceptions.MethodNotFoundException: No methods matching the name(s) getColumnCount were found in the class hierarchy of class java.lang.Object.
at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1720)
at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1745)
at org.powermock.reflect.internal.WhiteboxImpl.getBestMethodCandidate(WhiteboxImpl.java:983)
at org.powermock.core.MockGateway$MockInvocation.findMethodToInvoke(MockGateway.java:317)
at org.powermock.core.MockGateway$MockInvocation.init(MockGateway.java:356)
at org.powermock.core.MockGateway$MockInvocation.<init>(MockGateway.java:307)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:142)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:125)
at com.datafiniti.utils.mysqlconnpool.MysqlConnPoolTests.executeStringQuery(MysqlConnPoolTests.java:149)
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:316)
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:300)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
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:288)
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:208)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:121)
at …Run Code Online (Sandbox Code Playgroud) 我在测试用例中使用Junit4和Mockito,在下面的代码中,我试图模拟一个自动装配的对象,该对象在模拟类内抛出空指针异常,这意味着自动装配的对象未正确模拟
ContentDao.java
public class ContentDao {
@Autowired
private ConfigProperties configProperties;
public void fuction() {
int batchSize = configProperties.getBatchSize();
}
Run Code Online (Sandbox Code Playgroud)
ConfigProperties.java
@ConfigurationProperties(ignoreUnknownFields = false, prefix = "cleanup")
public class ConfigProperties {
private int batchSize;
public int getBatchSize() {
return batchSize;
}
}
Run Code Online (Sandbox Code Playgroud)
尝试模拟ConfigProperties。
@RunWith(MockitoJUnitRunner.class)
public class ContentDaoTest{
@InjectMocks
private ContentDao contentDao;
@Mock
private ConfigProperties configProperties;
@Test
public void functionTest(){
configProperties = mock(ConfigProperties.class);
when(configProperties.getBatchSize()).thenReturn(100);
ContentDao contentDao = new ContentDao();
contentDao.funtion();
}
Run Code Online (Sandbox Code Playgroud)
函数被调用,但是我在下面的行中得到了NPE。请帮助我被困在这里。
int batchSize = configProperties.getBatchSize();
Run Code Online (Sandbox Code Playgroud) 如何使用JUnit 4指定人类可读的测试名称(在IDE和测试报告中显示)?
理想情况下,通过自动转换实际的测试名称。