标签: junit5

在 JUNIT5 中的扩展之间共享存储数据

无论如何,我们是否可以使用 store 在 JUNIT 5 中的不同扩展之间共享数据

例子

public class Extension1{
     beforeAllCallback(){
          getStore(GLOBAL).put(projectId,"112");
     }
}

public class Extension2{
     beforeTestExecutionCallback(){
          System.out.println("projectId="+getStore(GLOBAL).get(projectId));
     }
}
Run Code Online (Sandbox Code Playgroud)

java junit5

0
推荐指数
1
解决办法
2061
查看次数

导入 org.junit.Test 抛出错误为“未找到测试运行程序“JUnit 5”的测试”

如果我org.junit.Test在运行 JUnit 时导入,它会给我一个错误,如“未找到 Test Runner JUnit 5 的测试”。

相反,如果我导入,org.junit.jupiter.api.Test那么我可以运行 JUnit 测试。

java junit mockito junit5

0
推荐指数
1
解决办法
5138
查看次数

使用 @ParameterizedTest 和 @RunWith(Parameterized.class) 时 JUnit5 (Vintage) 初始化错误

在尝试使用 JUnit 5 的参数化功能时,我偶然发现了一个初始化错误。

@ExtendWith(MockitoExtension.class)
@RunWith(Parameterized.class)
public class ServiceTest {

    @InjectMocks
    Service service;

    private static Stream<Arguments> getArguments() {
        return Stream.of(
                Arguments.of("something", "result1", "result2"),
                Arguments.of("another", "result3", "result4")
        );
    }

    @ParameterizedTest
    @MethodSource("getArguments")
    @DisplayName("Test parseEndpoint method")
    void testMethod(String arg1, String result1, String result2) {

        final String[] strings = service.doSomething(arg1);

        assertEquals(result1, strings[0]);
        assertEquals(result2, strings[1]);
    }

}
Run Code Online (Sandbox Code Playgroud)

然后我可以看到我的测试正在由参数化引擎和 JUnit Vintage 单元运行。这里的问题是如何禁用这样的类只由 Parameterized.class 运行?!

parameterized mockito junit5

0
推荐指数
1
解决办法
2616
查看次数

Mockito 2 + Junit 5 NoSuchMethodError on AnnotationSupport.findAnnotation

我正在尝试将 JUnit 5 集成到 Eclipse Oxygen3 下。该项目已经有 Mockito 2。

我已经完成了https://www.baeldung.com/mockito-junit-5-extension 中建议的所有步骤,如下所示:

依赖项:

  • junit-木星引擎 5.5.0
  • junit-jupiter-api 5.5.0
  • junit-vintage-engine 5.5.0
  • junit-平台-跑步者 1.5.0
  • 模拟核心 2.28.2
  • mockito-junit-jupiter 2.28.2

代码:

public class Jupiter {

    public boolean isAlpha() {
        return true;
    }

}
Run Code Online (Sandbox Code Playgroud)

测试代码:

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; 
import java.util.Date;  
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)
public class JupiterTest {

    @InjectMocks
    private Jupiter jupiter;

    @BeforeEach
    public void setup() …
Run Code Online (Sandbox Code Playgroud)

java unit-testing mockito junit5

0
推荐指数
1
解决办法
2561
查看次数

无法模拟/间谍类 java.util.Optional

我正在尝试实现这个 JUnit 代码:

private BinlistsService binlistsService = Mockito.mock(BinlistsService.class);

@Mock
Optional<BinLists> binList = null;

@BeforeEach
    public void beforeEachTest() throws IOException {

        BinLists binLists = new BinLists();
        binLists.setId(1);
        ....

        binList = Optional.of(binLists);
    }

    @Test
    public void testBinCountryCheckFilterImpl() {

        when(binlistsService.findByName(anyString())).thenReturn(binList);

}
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误堆栈:

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class java.util.Optional
Mockito cannot mock/spy because :
 - final class
    at org.data
Run Code Online (Sandbox Code Playgroud)

你知道我该如何解决这个问题吗?

java junit mockito junit5

0
推荐指数
1
解决办法
5755
查看次数

如何使用 junit5 jupiter 引擎运行 @SpringBatchTest

我正在按照以下链接编写端到端的春季批处理作业测试。

https://docs.spring.io/spring-batch/docs/current/reference/html/testing.html#endToEndTesting

这告诉使用 @RunWith(SpringRunner.class) 注释您的测试类,这是 Junit4 功能,我的测试用例使用 junit5 的老式引擎工作正常。

由于我的其他非批处理相关测试用例在 jupiter 引擎上运行,因此我想在我的端到端 spring 批处理作业测试中使用相同的测试用例。如果我用@ExtendWith(SpringExtension.class) 替换@RunWith(SpringRunner.class),我可以看到没有自动装配的字段被实例化并且具有空值。

由于我是春季批次和木星的新手,我无法理解出了什么问题。

任何指针将不胜感激

junit 测试用例示例代码

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.configuration.annotation.BatchConfigurer;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.batch.test.JobRepositoryTestUtils;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringRunner;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import static org.assertj.core.api.Assertions.assertThat;

@Slf4j
@Testcontainers
@SpringBatchTest
@SpringBootTest
@RunWith(SpringRunner.class)
//@ExtendWith(SpringExtension.class) …
Run Code Online (Sandbox Code Playgroud)

spring-batch spring-boot junit5

0
推荐指数
1
解决办法
2372
查看次数

如何获取extensionContext中的变量值

如何将结果字段的值获取到我的 TestReporter 类中?

@ExtendWith({TestReporter.class})
private TestClass{
   String result;

   @Test
   void testA(){
     //some action here
     result = some result;
   }
}
Run Code Online (Sandbox Code Playgroud)
public class TestReporter implements BeforeAllCallback, BeforeTestExecutionCallback, AfterAllCallback,
       TestWatcher {
    private static ExtentHtmlReporter htmlReporter;
    private static ExtentReports extent;
    private static ExtentTest test;

    @Override
    public void beforeAll(ExtensionContext context) throws Exception {
       //set up extent report
    }


   @Override
   public void testSuccessful(ExtensionContext context) {
     //not possible, but desired
     test.pass(context.getElement.get("result"), MediaEntityBuilder.createScreenCaptureFromPath("test"+count+".png").build());

   }

}
Run Code Online (Sandbox Code Playgroud)

我一直在研究做到这一点的方法,但不确定我所寻找的是否可能或如何实施

java junit unit-testing junit5

0
推荐指数
1
解决办法
1722
查看次数

如何解决期望代码以引发异常的可抛出单元测试用例?

我试图写测试用例这种情况下,在此我期待SQLIntegrityConstraintViolationException,我试图断言使用断言相同的是通过抛出,但我得到断言错误的期待码养Throwable。如何解决这个问题,有人可以帮我解决这个问题。

我正在使用JUnit5.

如屏幕截图所示,该方法在应用异常情况后似乎没有运行

@Test
public void insertUpdateDatatypesizecountValidation() throws Exception {
    id = 0;
    StandAloneConnection standAloneConnection = new StandAloneConnection(
                        propertyFile);
    Connection conn = standAloneConnection.getConnection();
    assertThatThrownBy(() -> called.datas(conn, id))
            .hasMessage("Column 'ID' cannot be null")
            .isInstanceOf(SQLIntegrityConstraintViolationException.class);
}      

Run Code Online (Sandbox Code Playgroud)

java junit junit5

0
推荐指数
1
解决办法
164
查看次数

@MockBean 返回空对象

我正在尝试使用@MockBean;java 版本 11、Spring 框架版本 (5.3.8)、Spring Boot 版本 (2.5.1) 和 Junit Jupiter (5.7.2)。

    @SpringBootTest
    public class PostEventHandlerTest {
        @MockBean
        private AttachmentService attachmentService;

        @Test
        public void handlePostBeforeCreateTest() throws Exception {
            Post post = new Post("First Post", "Post Added", null, null, "", "");
            
            Mockito.when(attachmentService.storeFile("abc.txt", "")).thenReturn(new Attachment());
     
            PostEventHandler postEventHandler = new PostEventHandler();
            postEventHandler.handlePostBeforeCreate(post);
            verify(attachmentService, times(1)).storeFile("abc.txt", "");
       }
    }
Run Code Online (Sandbox Code Playgroud)
    @Slf4j
    @Component
    @Configuration
    @RepositoryEventHandler
    public class PostEventHandler {
           @Autowired
           private AttachmentService attachmentService;

           @Autowired
           private PostRepository postRepository;

           public void handlePostBeforeCreate(Post post) throws Exception {
             ...
             /* Here …
Run Code Online (Sandbox Code Playgroud)

java spring junit5 spring-boot-test

0
推荐指数
2
解决办法
68
查看次数

找不到 ParameterizedTest 和 ValueSource

我做了一个简单的项目,试图了解如何ParameterizedTest工作ValueSource

从下图中它找到了导入路径,但是当我尝试运行代码时它会抛出错误:

在此输入图像描述

还有 gradle 文件:

在此输入图像描述

这是整个项目的链接。

junit intellij-idea gradle junit5

-1
推荐指数
1
解决办法
1534
查看次数

模拟服务不使用带有 Autowire 的构造函数但使用 Java 方法

我想编辑此代码以使用模拟服务。这段代码工作正常:

@Service
public class BinCountryCheckFilterImpl {

    private RiskFilterService riskFilterService;
    private Terminals terminal;

    @Autowired
    public BinCountryCheckFilterImpl(Terminals terminal, RiskFilterService riskFilterService) {  
        this.terminal = terminal;
        this.riskFilterService = riskFilterService;
    }

    public void validateBinCountryCheckFilter(Terminals terminal) throws JAXBException, JsonProcessingException {

        List<RiskFilters> filter_list = riskFilterService.findRiskFiltersByTerminalIdAndType(terminal.getId(), "BinCountryCheckFilter");
    }
}
Run Code Online (Sandbox Code Playgroud)

JUnit 测试:

public class BinCountryCheckFilterImplTest    {

    @Test
    public void testBinCountryCheckFilterImpl() throws JsonProcessingException, JAXBException {
        //Arrange
        RiskFilterService riskFilterService = Mockito.mock(RiskFilterService.class);
        Terminals terminal = Mockito.mock(Terminals.class);

        BDDMockito.given(
            riskFilterService.findRiskFiltersByTerminalIdAndType(anyInt(), anyString()))
            .willReturn(riskFiltersList);

        int expectedInt = 11;
        String expectedString = "BinCountryCheckFilter";

        when(terminal.getId()).thenReturn(expectedInt);

        BinCountryCheckFilterImpl binCountryCheckFilterImpl = …
Run Code Online (Sandbox Code Playgroud)

java junit spring spring-boot junit5

-1
推荐指数
1
解决办法
269
查看次数

我的代码不考虑使用返回布尔值的方法的 Mockito

在我的 Java 代码中,我想用 Mockito 模拟一个返回布尔值的方法。事实上,它涉及一个计算停车价格的停车应用程序。在我使用 Junit5 和 Mockito 进行的测试中,我模拟了一个方法,该方法返回一个布尔值,如果该布尔值为真,则通过减少来计算价格。但我的模拟不起作用,我不知道为什么......

when(ticketDao.isRegularCustomer(any(String.class))).thenReturn(true);
Run Code Online (Sandbox Code Playgroud)

我希望这个模拟可以通过减少来计算价格。感谢您的帮助,这是我的代码。

    @ExtendWith(MockitoExtension.class)
    public class FareCalculatorServiceTest {

    private static FareCalculatorService fareCalculatorService;
    private Ticket ticket;

    @Mock
    private static TicketDao ticketDao;

    @BeforeAll
    private static void setUp() {
        fareCalculatorService = new FareCalculatorService();

    }

    @BeforeEach
    private void setUpPerTest() {
        ticket = new Ticket();
        //when(ticketDao.isRegularCustomer(any())).thenReturn(false);
    }


    @Test
    public void feature2CalculateFareBikeWith5PerCentReduceIfRegularCustomer(){
        Date inTime = new Date();
        inTime.setTime( System.currentTimeMillis() - (45 * 60 * 1000) );//45MIN IN PARKING
        Date outTime = new Date();
        ParkingSpot parkingSpot = new ParkingSpot(1, …
Run Code Online (Sandbox Code Playgroud)

java unit-testing mockito junit5

-1
推荐指数
1
解决办法
785
查看次数