标签: junit4

如何使用 jmockit 模拟整个抽象类,但排除应在一个 JUnit4 测试用例中验证的一个或多个方法?

我在使用jmockit时遇到了以下问题。

我有一个抽象类,它还有许多具体(非抽象)实例方法,现在我想编写一个 JUnit4 测试用例来验证抽象类的一个非抽象和实例方法,但模拟类中的所有其他方法?

例如:

public class abstract Animal {
    public abstract void abstractMethod1();
    ......
    public abstract void abstractMethodN();

    public void method1() {
      System.out.println("Do something1 ...");
    }

    public void method2() {
      System.out.println("Do something2 ...");
    }

    ......
    public void methodN() {
      method1();
      method2();
      System.out.println("Do somethingN ...");
    }
}
Run Code Online (Sandbox Code Playgroud)

对于这个定义的类,我想编写一个 JUnit4 测试用例来仅验证 methodN 中的逻辑,所以我想模拟整个类。(对于method1和method2,mock或者不mock都可以。)怎么办?

java jmockit junit4

3
推荐指数
1
解决办法
4424
查看次数

Spring Junit 不工作

我正在尝试为我的带注释的类编写单元测试。当我取消时,我得到以下异常

java.lang.IllegalStateException: Could not load TestContextBootstrapper [null]. Specify @BootstrapWith's 'value' attribute or make the default bootstrapper class available.
    at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:143)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:105)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:152)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:143)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.findAllMergedAnnotations(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/Class;)Ljava/util/Set;
    at org.springframework.test.context.BootstrapUtils.resolveExplicitTestContextBootstrapper(BootstrapUtils.java:150)
    at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:126)
    ... 20 more
Run Code Online (Sandbox Code Playgroud)

下面是我的 pom.xml。我尝试使用 4.3.4 和 4.3.5 作为 spring 版本 …

java junit spring spring-test junit4

3
推荐指数
1
解决办法
3846
查看次数

使用自定义参数匹配器第二次调用 Mockito.when 时的 NPE

再会。

假设我有一个界面。该接口有一个方法,它接受某些类的一个或两个实例。在单元测试类中,我模拟了这个接口,并希望用这样的逻辑来模拟它:

  1. 如果参数与 template1 匹配则返回 value1
  2. 如果参数与 template2 匹配则返回 value2

当我仅模拟第一个案例时,测试运行顺利。当我添加第二种情况(以及第一种情况)时,测试会因 NPE 崩溃,如下所示:

java.lang.NullPointerException
at org.some.pkg.TestTest$ArgMatcher.matches(TestTest.java:54)
at org.some.pkg.TestTest$ArgMatcher.matches(TestTest.java:43)
at org.mockito.internal.invocation.TypeSafeMatching.apply(TypeSafeMatching.java:24)
at org.mockito.internal.invocation.MatcherApplicationStrategy.forEachMatcherAndArgument(MatcherApplicationStrategy.java:83)
at org.mockito.internal.invocation.InvocationMatcher.argumentsMatch(InvocationMatcher.java:152)
at org.mockito.internal.invocation.InvocationMatcher.matches(InvocationMatcher.java:81)
at org.mockito.internal.stubbing.InvocationContainerImpl.findAnswerFor(InvocationContainerImpl.java:91)
at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:87)
at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)
at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:35)
at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:63)
at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:49)
at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptAbstract(MockMethodInterceptor.java:128)
at org.some.pkg.Interface$MockitoMock$1549778145.callMe(Unknown Source)
at org.some.pkg.TestTest.test(TestTest.java:29)
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.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) …
Run Code Online (Sandbox Code Playgroud)

java unit-testing junit4 mockito

3
推荐指数
1
解决办法
1390
查看次数

如何在不重复代码的情况下在 Junit5 中测试接口的不同实现

请问如何为具有不同实现的接口编写junit 5测试?

例如,我有一个 interface Solution,具有不同的实现,例如SolutionI, SolutionII,我可以只编写一个测试类来测试两者吗?

有一个帖子展示了一个例子,但是如果有多个测试方法需要调用,我必须为每个测试方法传递参数。

请问有没有类似Junit4中使用的优雅方式

在 Junit4 中,我有一个非常优雅的代码示例如下

@RunWith(Parameterized.class)
public class SolutionTest {
  private Solution solution;

  public SolutionTest(Solution solution) {
    this.solution = solution;
  }

  @Parameterized.Parameters
  public static Collection<Object[]> getParameters() {
    return Arrays.asList(new Object[][]{
        {new SolutionI()},
        {new SolutionII()}
    });
  }
  // normal test methods
  @Test
  public void testMethod1() {

  }
}
Run Code Online (Sandbox Code Playgroud)

Junit 5 声称ExtendWith()是相似的,我尝试了以下代码

@ExtendWith(SolutionTest.SolutionProvider.class)
public class SolutionTest {
  private Solution solution;

  public SolutionTest(Solution solution) {
    System.out.println("Call constructor"); …
Run Code Online (Sandbox Code Playgroud)

java junit4 junit5

3
推荐指数
2
解决办法
1498
查看次数

如何在 Spring Boot 中使用mockito 模拟deleteById

如何在Spring Boot中使用mockito模拟mockRepository.deleteById() ?

spring junit4 mockito spring-boot

3
推荐指数
1
解决办法
5586
查看次数

将@WebMvcTest 与spring-boot 一起使用时如何排除@Configuration 类?

我正在为休息控制器编写junit。我只想加载与控制器相关的最小上下文,我认为这就是@WebMvcTest加载上下文的方式。但是 junit 正在加载完整的 Spring 上下文,并且由于无法创建某些 bean 而失败。

我已经搜索并阅读了许多关于 stackoverflow 的问题,但没有一个解决方案可以排除特定的配置。为控制器编写junit时如何加载最小上下文?或者有什么办法可以排除一些配置类?我使用的是 Spring-boot 2.2.2.RELEASE、Java 8 和 Junit 4。

Junit(我试图排除加载一些 bean 和配置,但它不起作用):

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = OrderController.class, excludeFilters = {@Filter(classes = Configuration.class), @Filter(type = FilterType.REGEX, pattern = "com\\.foo\\..*")})
@TestPropertySource(properties = { "spring.cloud.config.server.bootstrap:false" })
public class OrderControllerTest {

    @MockBean
    private OrderService orderService;


    @Autowired
    private MockMvc mockMvc;

    @Test
    public void test() throws Exception {
        mockMvc.perform(get("/internal/order/123"));
        // Further code to verify the response
    }

}
Run Code Online (Sandbox Code Playgroud)

控制器

@Slf4j
@Validated
@RestController
@RequestMapping("/internal")
public class OrderController {

    @Autowired …
Run Code Online (Sandbox Code Playgroud)

java junit4 spring-boot

3
推荐指数
1
解决办法
2841
查看次数

如何在 Gradle 构建文件中正确排除“junit-vintage-engine”?

使用此配置时,我收到initializationErrorJUnit Vintage 的:

testImplementation group: 'org.springframework.boot', name: 'spring-boot-starter-test'
Run Code Online (Sandbox Code Playgroud)

但使用此配置@RunWith注释无法解决:

testImplementation (group: 'org.springframework.boot', name: 'spring-boot-starter-test') {
    exclude group: 'org.junit.vintage', name: 'junit-vintage-engine', version: '5.7.0-M1'
}
Run Code Online (Sandbox Code Playgroud)

如何正确排除 JUnit Vintage 模块?

junit junit4 gradle junit5 junit-vintage

3
推荐指数
1
解决办法
5517
查看次数

Spring Boot中JPA Repository的Save方法的单元测试

你能告诉我我应该如何使用 Mockito 和 JUnit 为这段代码编写单元测试吗?StudentRepository 是一个扩展 JPA Repository 的接口。

public class StudentService {
    @Autowired
    StudentRepository studentRepository;
    
    public void saveStudentDetails(StudentModel student) {
        Student stud = new Student();
        stud.setStudentId(student.getStudentId());
        stud.setStudentName(student.getStudentName());
        studentRepository.save(stud);
    }
}
Run Code Online (Sandbox Code Playgroud)

junit junit4 mockito spring-boot

3
推荐指数
2
解决办法
3154
查看次数

如何强制 gradle 在 junit 4 和 junit 5 测试套件失败的情况下继续构建

我有一个项目,由 junit 4 和 5 实现测试。有些测试需要存在数据库,有什么方法可以标记这些特定测试(TestSuite 是答案吗?),所以 gradle 继续构建,即使那些测试失败了?

我不想跳过其他测试,而只想跳过这些特定测试。

我使用的是 junit 5 vintage,所以我的测试任务同时运行 junit 4 和 junit 5 测试。

junit junit4 gradle junit5

3
推荐指数
1
解决办法
7134
查看次数

如何将JUnit4的测试通过/失败结果记录到文件中?

当给定的JUnit4测试运行时,我希望它生成所有TestResults的日志文件.我不想通过CI/ant/maven调用它.我想在任何时候从任何地方调用JUnit测试时运行它.如果那是不可能的,那么我想编写我自己的运行器,它有问题地调用我的AllTestSuites类并记录所有结果本身.

这将是我的一个测试类:

public class SimpleTestSuite extends TestCase{

    @Test
    public void simpleTestPass() {
        assertTrue(true);
    }

    @Test
    public void simpleTestFail() {
        assertTrue(false);
    }

    @Test
    public void simpleTestException() {
        throw new RuntimeException();
    }

}
Run Code Online (Sandbox Code Playgroud)

我将它包含在TestSuite中,其中包含我要运行的所有测试套件:

@RunWith(Suite.class)
@Suite.SuiteClasses({SimpleTestSuite.class, ExampleSuite.class,})
public final class AllTestSuites {}
Run Code Online (Sandbox Code Playgroud)

我想调用AllTestSuites并让它生成一个日志文件,如下所示.请记住,我更喜欢捕获JUnit4框架结果总线上的内容,而不是重新创建/创建新的测试运行器.

simpleTestPass - pass - 1/1 assertions passed
simpleTestFail - fail - 0/1 assertions passed
simpleTestException - exception - stacktrace as follows...
Run Code Online (Sandbox Code Playgroud)

java junit junit4

2
推荐指数
1
解决办法
6819
查看次数