鉴于以下 JUnit 测试,surefire 将运行TestA两次TestB。第一次是单独测试,第二次是作为测试套件的一部分。这似乎是一种不受欢迎的行为。事实上,流行的 IDE(例如 IntelliJ)只会作为测试套件的一部分运行一次测试。
这是一个错误吗?有没有办法配置 Surefire-plugin 使其仅作为测试套件的一部分运行?
GitHub上提供示例项目
@RunWith(Suite.class)
@Suite.SuiteClasses({TestA.class, TestB.class})
public class TestSuite
{}
public class TestA {
@Test
public void test() {
System.out.println("=== RUN " + this.getClass());
}
}
public class TestB {
@Test
public void test() {
System.out.println("=== RUN " + this.getClass());
}
}
Run Code Online (Sandbox Code Playgroud) 我不明白为什么 maven-surefire-plugin 不运行 jUnit4 测试。我的 pom 是(无法在此处添加它,因为“它看起来帖子主要是代码”):http://pastebin.com/Jj3iJZpY
当我执行mvn clean testcmd窗口时显示:
C:\Users\maya\git\services>mvn clean test
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building services 1.0.18
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ services ---
[INFO] Deleting C:\Users\maya\git\services\target
[INFO]
[INFO] --- maven-mule-plugin:1.9:attach-test-resources (default-attach-test-resources) @ services ---
[INFO] attaching test resource C:\Users\maya\git\services\src\main\app
[INFO]
[INFO] --- build-helper-maven-plugin:1.7:add-resource (add-resource) @ services ---
[INFO]
[INFO] --- maven-resources-plugin:2.7:resources (default-resources) @ services ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 4 …Run Code Online (Sandbox Code Playgroud) 如何在 JUnit 中模拟“System.getenv("...")”。
目前我正在做:
@RunWith(Parameterized.class)
@PowerMockRunnerDelegate(PowerMockRunner.class)
@PrepareForTest(System.class)
public class TestClass extends BaseTest {
public TestClass(String testCase) {
this.testCase = testCase;
}
@Before
@Override
public final void initTable() throws Throwable {
super.initTable();
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getenv("ENV_VAR1")).thenReturn("1234");
}
...
}
Run Code Online (Sandbox Code Playgroud)
我同时使用 PowerMock 和 Parameterizedrunner。
我得到以下异常行:
PowerMockito.when(System.getenv("ENV_VAR1")).thenReturn("1234");
Run Code Online (Sandbox Code Playgroud)
例外:
org.mockito.exceptions.base.MockitoException:
'afterPropertiesSet' is a *void method* and it *cannot* be stubbed with a *return value*!
Voids are usually stubbed with Throwables:
doThrow(exception).when(mock).someVoidMethod();
***
Run Code Online (Sandbox Code Playgroud) 我有一个非常简单的测试类,用于在 Android 上运行 espresso 测试,如下所示:
import android.util.Log;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.IOException;
@RunWith(JUnit4.class)
public class Wtf {
private static class TestResources extends ExternalResource {
protected void before() {
println("before() TestResources");
}
protected void after() {
println("after() TestResources");
}
}
@ClassRule
public static final TestResources res = new TestResources();
@BeforeClass
public static void setUpClass() {
println("@BeforeClass setUpClass()");
}
@AfterClass
public static void tearDownClass() throws IOException { …Run Code Online (Sandbox Code Playgroud) 我正在开发一个 Spring Boot 项目,我有许多实体类和 DTO 类,其中大部分是 getter 和 setter。
有没有任何方法或插件可以为所有 Entity 和 DTO 类创建 junit 测试用例。只是为了提高测试覆盖率。
目前使用的框架有 Spring boot、Hibernate、Junit 4.12、Mockito。Java 1.8,intellij IDE。例如:`
@Entity
@Table(name = "xyz")
public class Xyz {
@Id
@GeneratedValue(strategy = IDENTITY)
public Integer id;
@Column(name = "col1")
public Integer col1;
@Column(name = "col2")
public Integer co2;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
};`
Run Code Online (Sandbox Code Playgroud) 一个问题:
当我做类似的事情时:
package path.to.common.package.test;
@BeforeClass
public class CommonTestSetup {
public void setUp() {
// Setup Stiff
}
}
Run Code Online (Sandbox Code Playgroud)
和同一个包中的另一个类设置:
package path.to.common.package.test;
public class TestTest extends CommonTestSetup {
@Test
public void testGetTestReturnsCorrectStrings() {
// do asserts etc
}
}
Run Code Online (Sandbox Code Playgroud)
然后对testGetTestReturnsCorrectStrings我执行 JUnit 测试时出现错误:
org.junit.runners.model.InvalidTestClassError: Invalid test class 'org.junit.runner.manipulation.Filter':
1. No runnable methods
at org.junit.runners.ParentRunner.validate(ParentRunner.java:456)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:99)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:84)
at org.junit.runners.JUnit4.<init>(JUnit4.java:23)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:66)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:37)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:66)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:39)
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:36)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createFilteredTest(JUnit4TestLoader.java:80)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:71)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:46)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:523) …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试一个方法是否创建一个对象。我几乎可以使用 PowerMockito.verifyNew().withArguments() 来工作,但是,传递给构造函数的参数是一个对象和一个对象的 ArrayList。测试的输出是:实际
invocationSubstitute.performSubstitutionLogic(
1,
6,
11,
13,
[au.edu.sccs.csp3105.NBookingPlanner.Person@2449cff7],
au.edu.sccs.csp3105.NBookingPlanner.Room@62da83ed,
"description"
);
Run Code Online (Sandbox Code Playgroud)
预期的
invocationSubstitute.performSubstitutionLogic(
1,
6,
11,
13,
[au.edu.sccs.csp3105.NBookingPlanner.Person@40bffbca],
au.edu.sccs.csp3105.NBookingPlanner.Room@42a9a63e,
"description"
);
Run Code Online (Sandbox Code Playgroud)
我可以看到问题是对象是相同类型但不是同一对象,有没有办法说预期对象是正确的类型?
测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Planner.class, Meeting.class})
public class MonthInput {
Planner planner;
@Rule
public final TextFromStandardInputStream systemInMock = emptyStandardInputStream();
@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();
@SuppressWarnings("deprecation")
@Before
public void setup() throws Exception {
Meeting meetingMock = Mockito.mock(Meeting.class);
PowerMockito.whenNew(Meeting.class).withAnyArguments().thenReturn(meetingMock);
}
@Test
public void MonthInputofless5() throws Exception {
// make spy
planner = Mockito.spy(Planner.class);
//override main menu with do …Run Code Online (Sandbox Code Playgroud) 我正在学习junit使用 Spring Boot 进行测试,我正在尝试为课堂编写测试用例AccountController。帐户控制器依赖于帐户服务。我用的 mockito是那个。但我收到错误,因为与模拟的交互为零
账户控制器
@GetMapping("/findAccountData")
public ResponseEntity<List<Tuple>> populateGridViews(@RequestParam(value="sClientAcctId",required=false) String sClientAcctId,
@RequestParam(value="sAcctDesc",required=false) String sAcctDesc,
@RequestParam(value="sInvestigatorName",required=false)String sInvestigatorName,
@RequestParam(value="sClientDeptId",required=false) String sClientDeptId) throws Exception {
return ResponseEntity.ok(accService.populateGridViews(sClientAcctId, sAcctDesc,sInvestigatorName,sClientDeptId));
}
Run Code Online (Sandbox Code Playgroud)
账户服务
public List<Tuple> populateGridViews(String sClientAcctId, String sAcctDesc, String sInvestigatorName,
String sClientDeptId)throws Exception{
QAccount account = QAccount.account;
QDepartment department = QDepartment.department;
QAccountCPCMapping accountCPCMapping = QAccountCPCMapping.accountCPCMapping;
QInvestigator investigator = QInvestigator.investigator;
JPAQuery<Tuple> query = new JPAQuery<Tuple>(em);
query.select(Projections.bean(Account.class, account.sClientAcctId, account.sAcctDesc, account.sLocation,
Projections.bean(Department.class, department.sDeptName, department.sClientDeptId).as("department"),
Projections.bean(Investigator.class, investigator.sInvestigatorName).as("investigator"),
Projections.bean(AccountCPCMapping.class, accountCPCMapping.sCCPCode).as("accountCPC"))).from(account)
.innerJoin(account.department, department).innerJoin(account.accountCPC, accountCPCMapping)
.innerJoin(account.investigator, …Run Code Online (Sandbox Code Playgroud) 我正在 android 中编写仪器测试,但是当我导入jUnit(使用@RunWith注释)时,它无法找到 jUnit,但我已经在单元测试中(在test文件夹下)使用 jUnit 。我什至无法开始编写测试。
同样的事情也发生在AndroidJUnit4课堂上。
我已将这些内容包含在build.gradle:
testCompile brazilGradle.testbuild('junit')
androidTestCompile brazilGradle.testbuild('AndroidSupportTestPackage-rules')
androidTestCompile brazilGradle.testbuild('AndroidSupportTestPackage-runner')
Run Code Online (Sandbox Code Playgroud)
我也在 defaultConfig 中包含了这个:
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
Run Code Online (Sandbox Code Playgroud)
为什么它在一个文件夹中工作而不在另一个文件夹中工作?
因此,我一直在对 Android 应用程序进行单元测试,虽然在某些情况下我会使用失败场景进行测试,但我并没有按照这个答案建议的方式来测试它们(在 JUnit 测试中尝试 catch)。
我按照下面代码中显示的方式对其进行测试。答案是建议您应该在测试方法签名上添加“抛出异常”,因为如果它实际上抛出了您不期望的异常,那么它将导致测试失败。然而,我尝试了使用和不使用那段代码,但它都以同样的方式失败。上面提供的答案也使用我没有使用过的“规则”来进行这种测试,因为我需要的一切都在我的 try catch 块中,并且实例化是在 @Before 方法内完成的。
@Test
public void testMethod() {
try{
//code that will throw exception
fail("Exception was not thrown");
} catch (/* types of exceptions */) {
//my asserts
}
}
Run Code Online (Sandbox Code Playgroud)
我所追求的是哪种方法被认为是“最佳实践”以及其背后的原因。
junit4 ×10
java ×6
junit ×4
android ×3
mockito ×2
powermockito ×2
unit-testing ×2
maven ×1
mule ×1
querydsl ×1
spring-boot ×1
spring-test ×1