Java Code Examples for org.junit.jupiter.api.BeforeEach

The following examples show how to use org.junit.jupiter.api.BeforeEach. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: gaia   Source File: TerraformModuleRepositoryIT.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() {
    // sample teams
    Team team1 = new Team("team1");
    Team team2 = new Team("team2");

    // sample owners
    bob = new User("Bob", null);

    // saving sample modules
    TerraformModule module1 = new TerraformModule();
    module1.setId("Module 1");
    module1.setAuthorizedTeams(List.of(team1));
    module1.getModuleMetadata().setCreatedBy(bob);

    TerraformModule module2 = new TerraformModule();
    module2.setId("Module 2");
    module2.setAuthorizedTeams(List.of(team1, team2));
    module2.getModuleMetadata().setCreatedBy(bob);

    terraformModuleRepository.deleteAll();
    terraformModuleRepository.saveAll(List.of(module1, module2));
}
 
Example 2
Source Project: incubator-tuweni   Source File: ServerTofaTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void startServer(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  knownClientsFile = tempDir.resolve("known-clients.txt");
  Files.write(knownClientsFile, Arrays.asList("#First line", "foobar.com " + DUMMY_FINGERPRINT));

  SelfSignedCertificate serverCert = SelfSignedCertificate.create();
  HttpServerOptions options = new HttpServerOptions();
  options
      .setSsl(true)
      .setClientAuth(ClientAuth.REQUIRED)
      .setPemKeyCertOptions(serverCert.keyCertOptions())
      .setTrustOptions(VertxTrustOptions.trustClientOnFirstAccess(knownClientsFile, false))
      .setIdleTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  httpServer = vertx.createHttpServer(options);
  SecurityTestUtils.configureAndStartTestServer(httpServer);
}
 
Example 3
Source Project: incubator-tuweni   Source File: ServerRecordTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void startServer(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  knownClientsFile = tempDir.resolve("known-clients.txt");
  Files.write(knownClientsFile, Arrays.asList("#First line", "foobar.com " + DUMMY_FINGERPRINT));

  SelfSignedCertificate serverCert = SelfSignedCertificate.create();
  HttpServerOptions options = new HttpServerOptions();
  options
      .setSsl(true)
      .setClientAuth(ClientAuth.REQUIRED)
      .setPemKeyCertOptions(serverCert.keyCertOptions())
      .setTrustOptions(VertxTrustOptions.recordClientFingerprints(knownClientsFile, false))
      .setIdleTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  httpServer = vertx.createHttpServer(options);
  SecurityTestUtils.configureAndStartTestServer(httpServer);
}
 
Example 4
Source Project: ecs-logging-java   Source File: EcsEncoderTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() {
    LoggerContext context = new LoggerContext();
    logger = context.getLogger(getClass());
    appender = new OutputStreamAppender();
    appender.setContext(context);
    logger.addAppender(appender);
    EcsEncoder ecsEncoder = new EcsEncoder();
    ecsEncoder.setServiceName("test");
    ecsEncoder.setIncludeMarkers(true);
    ecsEncoder.setStackTraceAsArray(true);
    ecsEncoder.setIncludeOrigin(true);
    ecsEncoder.addAdditionalField(new EcsEncoder.Pair("foo", "bar"));
    ecsEncoder.addAdditionalField(new EcsEncoder.Pair("baz", "qux"));
    ecsEncoder.setEventDataset("testdataset.log");
    ecsEncoder.start();
    appender.setEncoder(ecsEncoder);
    appender.start();
}
 
Example 5
Source Project: ofdrw   Source File: VirtualContainerTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void init() throws IOException {
    Path path = Paths.get(target);
    if (Files.exists(path)) {
        FileUtils.deleteDirectory(path.toFile());
    } else {
        path = Files.createDirectories(path);
    }
    vc = new VirtualContainer(path);
}
 
Example 6
Source Project: incubator-tuweni   Source File: ServerCaOrTofaTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void startServer(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  knownClientsFile = tempDir.resolve("known-clients.txt");
  Files.write(knownClientsFile, Arrays.asList("#First line", "foobar.com " + DUMMY_FINGERPRINT));

  SelfSignedCertificate serverCert = SelfSignedCertificate.create();
  HttpServerOptions options = new HttpServerOptions();
  options
      .setSsl(true)
      .setClientAuth(ClientAuth.REQUIRED)
      .setPemKeyCertOptions(serverCert.keyCertOptions())
      .setTrustOptions(VertxTrustOptions.trustClientOnFirstAccess(knownClientsFile))
      .setIdleTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  httpServer = vertx.createHttpServer(options);
  SecurityTestUtils.configureAndStartTestServer(httpServer);
}
 
Example 7
Source Project: springdoc-openapi   Source File: SpringDocApp9Test.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void init() throws IllegalAccessException {
	Field convertersField2 = FieldUtils.getDeclaredField(ObjectMapper.class, "_mixIns", true);
	SimpleMixInResolver _mixIns = (SimpleMixInResolver) convertersField2.get(Json.mapper());
	Field convertersField3 = FieldUtils.getDeclaredField(SimpleMixInResolver.class, "_localMixIns", true);
	Map<ClassKey, Class<?>> _localMixIns = (Map<ClassKey, Class<?>>) convertersField3.get(_mixIns);
	Iterator<Map.Entry<ClassKey, Class<?>>> it = _localMixIns.entrySet().iterator();
	while (it.hasNext()) {
		Map.Entry<ClassKey, Class<?>> entry = it.next();
		if (entry.getKey().toString().startsWith("org.springframework")) {
			springMixins.put(entry.getKey(), entry.getValue());
			it.remove();
		}
	}

}
 
Example 8
@BeforeEach
void setUp() throws ExecutionException, InterruptedException {
    testBucketAccessor.clear(gcsPrefix);

    final Properties adminClientConfig = new Properties();
    adminClientConfig.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers());
    adminClient = AdminClient.create(adminClientConfig);

    final Map<String, Object> producerProps = new HashMap<>();
    producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers());
    producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
            "org.apache.kafka.common.serialization.ByteArraySerializer");
    producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
            "org.apache.kafka.common.serialization.ByteArraySerializer");
    producer = new KafkaProducer<>(producerProps);

    final NewTopic newTopic0 = new NewTopic(TEST_TOPIC_0, 4, (short) 1);
    final NewTopic newTopic1 = new NewTopic(TEST_TOPIC_1, 4, (short) 1);
    adminClient.createTopics(Arrays.asList(newTopic0, newTopic1)).all().get();

    connectRunner = new ConnectRunner(pluginDir, kafka.getBootstrapServers(), OFFSET_FLUSH_INTERVAL_MS);
    connectRunner.start();
}
 
Example 9
Source Project: alchemy   Source File: HibernateTimeZoneIT.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setup() {
    dateTimeWrapper = new DateTimeWrapper();
    dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:50:00.0Z"));
    dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:50:00.0"));
    dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z"));
    dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:30:00.0Z"));
    dateTimeWrapper.setLocalTime(LocalTime.parse("14:30:00"));
    dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:30:00+02:00"));
    dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10"));

    dateTimeFormatter = DateTimeFormatter
        .ofPattern("yyyy-MM-dd HH:mm:ss.S")
        .withZone(ZoneId.of("UTC"));

    timeFormatter = DateTimeFormatter
        .ofPattern("HH:mm:ss")
        .withZone(ZoneId.of("UTC"));

    dateFormatter = DateTimeFormatter
        .ofPattern("yyyy-MM-dd");
}
 
Example 10
@BeforeEach
public void setup() {
    servletContext = spy(new MockServletContext());
    doReturn(mock(FilterRegistration.Dynamic.class))
        .when(servletContext).addFilter(anyString(), any(Filter.class));
    doReturn(mock(ServletRegistration.Dynamic.class))
        .when(servletContext).addServlet(anyString(), any(Servlet.class));

    env = new MockEnvironment();
    props = new JHipsterProperties();

    webConfigurer = new WebConfigurer(env, props);
}
 
Example 11
Source Project: vividus   Source File: PropertyMappedDataProviderTests.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
void beforeEach() throws IOException
{
    String propertyPrefix = "prefix";
    when(propertyMapper.readValues(propertyPrefix, String.class)).thenReturn(Collections.singletonMap(KEY, VALUE));
    provider = new PropertyMappedDataProvider<>(propertyMapper, propertyPrefix, String.class);
}
 
Example 12
@BeforeEach
void setupSchema() {
    TypeDefinitionRegistry typeDefs = new SchemaParser().parse(tracingSDL);
    RuntimeWiring resolvers = RuntimeWiring.newRuntimeWiring()
            .type("Query", builder ->
                    // return two items
                    builder.dataFetcher("widgets", env -> {
                        ArrayList<Object> objects = new ArrayList<>(2);
                        objects.add(new Object());
                        objects.add(new Object());
                        return objects;
                    }).dataFetcher("listOfLists", env -> {
                        ArrayList<ArrayList<Object>> lists = new ArrayList<>(2);
                        lists.add(new ArrayList<>(2));
                        lists.add(new ArrayList<>(2));
                        lists.get(0).add(new Object());
                        lists.get(0).add(new Object());
                        lists.get(1).add(new Object());
                        lists.get(1).add(new Object());
                        return lists;
                    })
                            .dataFetcher("listOfScalars", env -> new String[]{"one", "two", "three"}))
            .type("Widget", builder ->
                    // Widget.foo works normally, Widget.bar always throws an error
                    builder.dataFetcher("foo", env -> "hello world")
                            .dataFetcher("bar", env -> {
                                throw new GraphQLException("whoops");
                            }))
            .build();

    GraphQLSchema graphQLSchema = new SchemaGenerator().makeExecutableSchema(typeDefs, resolvers);
    graphql = GraphQL.newGraphQL(graphQLSchema)
            .instrumentation(new FederatedTracingInstrumentation())
            .build();
}
 
Example 13
@BeforeEach
public void setup() {
    mockMvc = MockMvcBuilders.standaloneSetup(controller)
        .setControllerAdvice(exceptionTranslator)
        .setMessageConverters(jacksonMessageConverter)
        .build();
}
 
Example 14
@BeforeEach
public void setup() {
    ClientForwardController clientForwardController = new ClientForwardController();
    this.restMockMvc = MockMvcBuilders
        .standaloneSetup(clientForwardController, new TestController())
        .build();
}
 
Example 15
Source Project: ethsigner   Source File: IntegrationTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
  jsonRpc = new JsonRpc2_0Web3j(null, 2000, defaultExecutorService());
  eeaJsonRpc = new JsonRpc2_0Eea(null);
  if (clientAndServer.isRunning()) {
    clientAndServer.reset();
  }
}
 
Example 16
@BeforeEach
void setUp() {
  sendTransaction = new SendTransaction();
  sendRawTransaction = new SendRawTransaction(jsonRpc(), credentials);
  final TransactionCountResponder getTransactionResponse =
      new TransactionCountResponder(nonce -> nonce.add(ONE), ETH_GET_TRANSACTION_COUNT);
  clientAndServer.when(getTransactionResponse.request()).respond(getTransactionResponse);
}
 
Example 17
Source Project: realworld-api-quarkus   Source File: UsersServiceImplTest.java    License: MIT License 5 votes vote down vote up
@BeforeEach
public void beforeEach() {
  userRepository = mock(UserRepository.class);
  tokenProvider = mock(TokenProvider.class);
  hashProvider = mock(HashProvider.class);
  usersService = new UsersServiceImpl(userRepository, tokenProvider, hashProvider);
}
 
Example 18
Source Project: ecs-logging-java   Source File: Log4j2EcsLayoutTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {
    ctx = new LoggerContext("Test");
    ctx.reconfigure();
    ctx.getConfiguration().getProperties().put("node.id", "foo");

    root = ctx.getRootLogger();

    for (final Appender appender : root.getAppenders().values()) {
        root.removeAppender(appender);
    }
    EcsLayout ecsLayout = EcsLayout.newBuilder()
            .setConfiguration(ctx.getConfiguration())
            .setServiceName("test")
            .setIncludeMarkers(true)
            .setIncludeOrigin(true)
            .setStackTraceAsArray(true)
            .setEventDataset("testdataset.log")
            .setAdditionalFields(new KeyValuePair[]{
                    new KeyValuePair("cluster.uuid", "9fe9134b-20b0-465e-acf9-8cc09ac9053b"),
                    new KeyValuePair("node.id", "${node.id}"),
                    new KeyValuePair("empty", "${empty}"),
                    new KeyValuePair("clazz", "%C"),
                    new KeyValuePair("custom", "%custom"),
                    new KeyValuePair("emptyPattern", "%notEmpty{%invalidPattern}"),
            })
            .build();

    listAppender = new ListAppender("ecs", null, ecsLayout, false, false);
    listAppender.start();
    root.addAppender(listAppender);
    root.setLevel(Level.DEBUG);
}
 
Example 19
Source Project: ethsigner   Source File: CorsAcceptanceTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() {
  final NodeConfiguration nodeConfig =
      new NodeConfigurationBuilder().cors(AUTHORISED_DOMAIN).build();
  final SignerConfiguration signerConfig = new SignerConfigurationBuilder().build();

  ethNode = new BesuNode(DOCKER, nodeConfig);
  ethNode.start();
  ethNode.awaitStartupCompletion();

  ethSigner = new Signer(signerConfig, nodeConfig, ethNode.ports());
  ethSigner.start();
  ethSigner.awaitStartupCompletion();
}
 
Example 20
Source Project: kogito-runtimes   Source File: QueryCepTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void prepare() {
    String drl = "package org.drools.compiler.integrationtests\n" +
            "import " + TestEvent.class.getCanonicalName() + "\n" +
            "declare TestEvent\n" +
            "    @role( event )\n" + 
            "end\n" + 
            "query EventsFromStream\n" + 
            "    $event : TestEvent() from entry-point FirstStream\n" + 
            "end\n" + 
            "query ZeroToNineteenSeconds\n" + 
            "    $event : TestEvent() from entry-point FirstStream\n" + 
            "    $result : TestEvent ( this after [0s, 19s] $event) from entry-point SecondStream\n" + 
            "end\n";
    
    final KieServices ks = KieServices.Factory.get();
    KieFileSystem kfs = ks.newKieFileSystem();
    KieModuleModel kmodule = ks.newKieModuleModel();

    KieBaseModel baseModel = kmodule.newKieBaseModel("defaultKBase")
            .setDefault(true)
            .setEventProcessingMode(EventProcessingOption.STREAM);
    baseModel.newKieSessionModel("defaultKSession")
            .setDefault(true)
            .setClockType(ClockTypeOption.get("pseudo"));

    kfs.writeKModuleXML(kmodule.toXML());
    kfs.write( ResourceFactory.newByteArrayResource(drl.getBytes())
                              .setTargetPath("org/drools/compiler/integrationtests/queries.drl") );

    assertTrue(ks.newKieBuilder(kfs).buildAll().getResults().getMessages().isEmpty());
    ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession();
    
    firstEntryPoint = ksession.getEntryPoint("FirstStream");
    secondEntryPoint = ksession.getEntryPoint("SecondStream"); 
    clock = ksession.getSessionClock();
}
 
Example 21
@BeforeEach
void before() {
    entityProperties.getPersist().setCryptoTransferAmounts(true);
    entityProperties.getPersist().setNonFeeTransfers(false);

    expectedEntityNum.clear();
    expectedNonFeeTransfersCount = 0;
    expectedTransactions.clear();
}
 
Example 22
Source Project: cloud-spanner-r2dbc   Source File: SpannerConnectionTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the mocks in the test.
 */
@BeforeEach
public void setupMocks() {
  this.mockClient = mock(Client.class);

  when(this.mockClient.beginTransaction(any(), any()))
      .thenReturn(Mono.just(Transaction.getDefaultInstance()));
  when(this.mockClient.commitTransaction(any(), any()))
      .thenReturn(Mono.just(CommitResponse.getDefaultInstance()));
  when(this.mockClient.rollbackTransaction(any(), any()))
      .thenReturn(Mono.empty());
}
 
Example 23
Source Project: vividus   Source File: WaitFactoryTests.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
void beforeEach()
{
    waitFactory = new WaitFactory();
    waitFactory.setTimeout(TIMEOUT);
    waitFactory.setPollingPeriod(TIMEOUT);
}
 
Example 24
Source Project: gaia   Source File: ModuleRestControllerTest.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {
    admin = new User("admin", null);

    john = new User("John Dorian", null);

    bobsTeam = new Team("bobsTeam");
    bob = new User("Bob Kelso", bobsTeam);
}
 
Example 25
Source Project: java-microservices-examples   Source File: UserMapperIT.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void init() {
    user = new User();
    user.setLogin(DEFAULT_LOGIN);
    user.setActivated(true);
    user.setEmail("[email protected]");
    user.setFirstName("john");
    user.setLastName("doe");
    user.setImageUrl("image_url");
    user.setLangKey("en");

    userDto = new UserDTO(user);
}
 
Example 26
Source Project: gaia   Source File: SettingsRepositoryTest.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {
    settings = new Settings();
    settings.setExternalUrl("externalUrl");
    settings.setDockerDaemonUrl("dockerDaemonUrl");

    settingsRepository = new SettingsRepository(mongoTemplate, settings);
}
 
Example 27
Source Project: sdn-rx   Source File: ReactiveWebApplicationTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setupData() throws IOException {
	try (BufferedReader moviesReader = new BufferedReader(
		new InputStreamReader(this.getClass().getResourceAsStream("/movies.cypher")));
		Session session = driver.session()) {

		session.writeTransaction(tx -> {
			tx.run("MATCH (n) DETACH DELETE n");
			String moviesCypher = moviesReader.lines().collect(Collectors.joining(" "));
			tx.run(moviesCypher);
			return null;
		});
	}

}
 
Example 28
Source Project: alchemy   Source File: UserServiceIT.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void init() {
    user = new User();
    user.setLogin(DEFAULT_LOGIN);
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(true);
    user.setEmail(DEFAULT_EMAIL);
    user.setFirstName(DEFAULT_FIRSTNAME);
    user.setLastName(DEFAULT_LASTNAME);
    user.setImageUrl(DEFAULT_IMAGEURL);
    user.setLangKey(DEFAULT_LANGKEY);

    when(dateTimeProvider.getNow()).thenReturn(Optional.of(LocalDateTime.now()));
    auditingHandler.setDateTimeProvider(dateTimeProvider);
}
 
Example 29
Source Project: ecs-logging-java   Source File: EcsFormatterTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {
    record.setInstant(Instant.ofEpochMilli(5));
    record.setSourceClassName("ExampleClass");
    record.setSourceMethodName("exampleMethod");
    record.setThreadID(7);
    record.setLoggerName("ExampleLogger");
}
 
Example 30
@SuppressWarnings({"rawtypes", "unchecked"})
@BeforeEach
public void setup() {

    responseBuilder = mock(ResponseBuilder.class);
    Response response = mock(Response.class);

    when((runtimeDelegate).createResponseBuilder()).thenReturn(responseBuilder);
    lenient().when((responseBuilder).status(any(StatusType.class))).thenReturn(responseBuilder);
    lenient().when((responseBuilder).entity(any())).thenReturn(responseBuilder);
    lenient().when((responseBuilder).build()).thenReturn(response);

    application = mock(Application.class);
    processes = mock(Processes.class);
    Process process = mock(Process.class);
    ProcessInstances instances = mock(ProcessInstances.class);
    processInstance = mock(ProcessInstance.class);
    error = mock(ProcessError.class);

    lenient().when(processes.processById(anyString())).thenReturn(process);
    lenient().when(process.instances()).thenReturn(instances);
    lenient().when(instances.findById(anyString())).thenReturn(Optional.of(processInstance));
    lenient().when(processInstance.error()).thenReturn(Optional.of(error));
    lenient().when(processInstance.id()).thenReturn("abc-def");
    lenient().when(processInstance.status()).thenReturn(ProcessInstance.STATE_ACTIVE);
    lenient().when(error.failedNodeId()).thenReturn("xxxxx");
    lenient().when(error.errorMessage()).thenReturn("Test error message");

    lenient().when(application.unitOfWorkManager()).thenReturn(new DefaultUnitOfWorkManager(new CollectingUnitOfWorkFactory()));
    resource = spy(new ProcessInstanceManagementResource(processes, application));
}