SpringTest etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
SpringTest etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

13 Haziran 2023 Salı

SpringTest Testcontainers @ServiceConnection

Giriş
Şu satırı dahil ederiz
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
Açıklaması şöyle
The @ServiceConnection removes the need to write @DynamicPropertySource property overrides.
Örnek
Şöyle yaparız
@SpringBootTest
public class ServiceConnectionFieldTest {

  @Container
  @ServiceConnection
  static PostgreSQLContainer postgres = new PostgreSQLContainer(DockerImageName.parse("postgres:15.1"))
      .withUsername("testUser")
      .withPassword("testSecret")
      .withDatabaseName("testDatabase");

  @BeforeAll
  static void setup(){
    postgres.start();
  }
  ...
}
@RestartScope Anotasyonu
Giriş
Şu satırı dahil ederiz
import org.springframework.boot.devtools.restart.RestartScope;
Örnek - 
Açıklaması şöyle
annotation which prevents the container restarts during automatic reloads by Spring Boot DevTools.

21 Ekim 2021 Perşembe

SpringTest Testcontainers Veri Tabanı Hazırlama

Örnek
Açıklaması şöyle
This custom specialization of the MySQLContainer builds a container based on mysql:latest, with a new schema HR, a user ‘docker’ and runs a setup script from src/test/resources/sql upon container startup.
Şöyle yaparız
import org.testcontainers.containers.BindMode;
import org.testcontainers.containers.MySQLContainer;

public class TestDBContainer extends MySQLContainer {

  public OurSQLContainer() {
    super("mysql:latest");
    withDatabaseName("HR")
      .withUsername("docker")
      .withPassword("docker")
      .withClasspathResourceMapping("sql/setup.sql", "/docker-entrypoint-initdb.d/", BindMode.READ_ONLY);
    }
}
Ama veri tabanını doldurmak uzun sürüyorsak kendi imajımızı hazırlarız. Şöyle yaparız
FROM mysql:latest

ENV MYSQL_ROOT_PASSWORD=root
ENV MYSQL_DATABASE=hr
ENV MYSQL_USER=docker
ENV MYSQL_PASSWORD=docker

COPY ./setup.sql /docker-entrypoint-initdb.d/

# necessary to persist the new database state when we commit the container
RUN cp -r /var/lib/mysql /var/lib/mysql-no-volume

CMD ["--datadir", "/var/lib/mysql-no-volume"]
Daha sonra bunu kullanırız. Şöyle yaparız
super(DockerImageName.parse("testdb:latest").asCompatibleSubstituteFor("mysql"));


21 Eylül 2021 Salı

SpringTest Testcontainers GenericContainer Sınıfı

GenericContainer Sınıfı
Şu satırı dahil ederiz
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.containers.wait.strategy.Wait;
Belirtilen docker image'ını çalıştırır

getHost metodu
Örnek
Şöyle yaparız
@Testcontainers
public class GenericContainerTest {

  private static final int INTERNAL_MARIO_PORT = 8080;

  @Container
  private GenericContainer marioContainer =
new GenericContainer(DockerImageName.parse("pengbai/docker-supermario"))
    .withExposedPorts(INTERNAL_MARIO_PORT);

  @Test
  public void testRunningMario() throws IOException {

    String host = marioContainer.getHost();
    int exposedPort = marioContainer.getMappedPort(INTERNAL_MARIO_PORT);

    URL url = new URL("http://" + host + ":" + exposedPort);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");

    assertEquals(200, con.getResponseCode());
  }
}
withCopyFileToContainer metodu
Örnek
Şöyle yaparız
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.utility.MountableFile;

String dockerImageName = "hazelcast/hazelcast:latest";
GenericContainer<?> hazelcastContainer = new GenericContainer<>(dockerImageName)
  .withExposedPorts(5701)
  .withCopyFileToContainer(MountableFile.forClasspathResource("/hazelcast-server.xml"),
					"/opt/hazelcast/config/hazelcast.xml")
  .withEnv("HAZELCAST_CONFIG", "/opt/hazelcast/config/hazelcast.xml");

hazelcastContainer.start();
witEnv metodu
Örnek
Şöyle yaparız
GenericContainer<?> container = new GenericContainer<>("...")
  .withExposedPorts(8080)
  .withNetwork(Network.newNetwork())
.withNetworkAliases("application")
.withEnv("JAVA_OPTS", "-Djava.net.preferIPv4Stack=true -Djava.net.preferIPv4Addresses=true") .waitingFor(Wait.forHealthcheck()); container.start();
withExposedPorts metodu
Örnek
Şöyle yaparız
@org.testcontainers.spock.Testcontainers
class RedisBackedCacheIntTest extends Specification {

  GenericContainer redis = new GenericContainer<>("redis:5.0.3-alpine")
    .withExposedPorts(6379)
}
withLogConsumer metodu
Container bilgilerini de loglar
Örnek
Şöyle yaparız
@Container
private GenericContainer marioContainer = 
  new GenericContainer(DockerImageName.parse("pengbai/docker-supermario"))
    .withLogConsumer(new Slf4jLogConsumer(LOGGER))
    .withExposedPorts(INTERNAL_MARIO_PORT);

9 Ağustos 2021 Pazartesi

SpringTest MockMultipartFile Sınıfı

Örnek
Elimizde şöyle bir kod olsun
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ApiOperation(value = "Saves File instance.", tags = {"File"})
@ApiResponses({
        @ApiResponse(code = 201, message = "A File was successfully created.")
})
public ResponseEntity create(@RequestPart(name = "model") @Valid FileCreationDto model, 
                             @RequestPart(name = "file") MultipartFile file) {
    try {
        model.setData(file.getBytes());
    } catch (IOException e) {
        return ResponseEntity.badRequest().build();
    }

  File fileCreated = fileService.create(model, file.getOriginalFilename());
  return ResponseEntity.status(HttpStatus.CREATED).body(fileCreated);
}
Şöyle yaparız
@Test
public void create_withName_OK() throws Exception {
  
  MockMultipartFile model = ...;
  MockMultipartFile file = ...;

  MvcResult result = mvc.perform(
    MockMvcRequestBuilders.multipart("/api/files")
      .file(model)
      .file(file))
      .andDo(print())
      .andExpect(status().isCreated())
      .andReturn();

  File parsed = jsonMapper.readValue(result.getResponse().getContentAsByteArray(), 
    new TypeReference<>() {});

  ...
}


3 Şubat 2021 Çarşamba

SpringTest @SpringJUnitWebConfig Anotasyonu

Giriş
Şu satırı dahil ederiz
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
Spring 5 ile geliyor. @SpringJUnitConfig ve @WebAppConfiguration anotasyonlarının bileşimi

Örnek
Şöyle yaparız
import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(MockitoExtension.class)
@SpringJUnitWebConfig(classes = {LoggerAspectTest.Config.class} )
@DisplayName("LoggerAspect Unit Tests")
public class LoggerAspectTest {

  @Autowired
  Logger loggerMock;
  // the configuration class used to load beans for the test
  static class Config{
    @Bean
    public Logger logger() {
      return Mockito.mock(Logger.class);
    }
  }
  // Canary test
  @Test
  @DisplayName("Canary Test")
  void canaryTest() {
    assertThat(loggerMock).isNotNull();
  }
}

29 Aralık 2020 Salı

SpringTest MockMvcResultMatchers Sınıfı

Giriş
Şu satırı dahil ederiz
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
content metodu
Örnek ver
cookie metodu
Örnek ver
flash metodu
Örnek ver
forwardedUrl metodu
Örnek ver
forwardedUrlPattern metodu
Örnek ver
forwardedUrlTemplate metodu
Örnek ver
handler metodu
Örnek ver
header metodu
Örnek ver

jsonPath metodu
Cevap olarak gelen json nesnesinin bir alanına erişmek için kullanılır
Örnek
Şöyle yaparız
@Test
public void should_parse_id_from_plain_string() throws Exception {
  //given
  final String emptyId = "00000000-0000-0000-0000-000000000000";

  //when
  mockMvc.perform(MockMvcRequestBuilders.get("/find-id/" + emptyId))

  //then
  .andExpect(status().isOk())
  .andExpect(jsonPath("$.id", equalTo(emptyId)));
}

model metodu
Örnek ver
redirectedUrl metodu
Örnek ver
redirectedUrlPattern metodu
Örnek ver
redirectedUrlTemplate metodu
Örnek ver
request metodu
Örnek ver
status metodu
Örnek ver
view metodu
Örnek ver
xpath metodu
Örnek ver

28 Aralık 2020 Pazartesi

SpringTest MockMvcRequestBuilders Sınıfı

Giriş
Şu satırı dahil ederiz
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
get metodu
Örnek
Şöyle yaparız
@Test
public void testGenerateStudent() throws Exception {

  Student student = new Student();
  student.setName("TestStudent");
  Mockito.when(studentService.getRandomStudent()).thenReturn(student);

  mockMvc.perform(MockMvcRequestBuilders.get("/generate-student"))
    .andExpect(MockMvcResultMatchers.status().isOk())
    .andDo(print())
    .andExpect(MockMvcResultMatchers.jsonPath("$.name").isNotEmpty());

}
multipart metodu
Örnek
Şöyle yaparız
MockMultipartFile file1 = ...
MockMultipartFile file2 = ...

MvcResult result = mvc.perform(
  MockMvcRequestBuilders.multipart("/api/files")
    .filefile1)
    .file(file2))
  .andDo(print())
  .andExpect(status().isCreated())
  .andReturn();
param metodu
@RequestParam için gereken veriyi gönderir

Örnek
Elimizde şöyle bir kod olsun
@RestController @RequiredArgsConstructor @Slf4j public class LinksController { private final LinksService linksService; @GetMapping("/validateLink-url") public UrlSafety validateLink(@RequestBody String link, @RequestParam("directSearch") boolean isDirectSearch) { ... } }
Şöyle yaparız
@WebMvcTest public class LinksControllerIntegrationTest { @Autowired private MockMvc mockMvc; @MockBean private LinksService linksService; @Test public void testValidateLinkDirectSearchTrue_WhenUrlExists_ShouldReturnValid() String url = "http://safe-url.com"; when(linksService.isSafeUrlByDirectSearch(url)).thenReturn(true); mockMvc.perform(get("/validateLink-url") .param("directSearch", "true") .content(url) .contentType(MediaType.TEXT_PLAIN) .accept(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(status().isOk()) .andExpect(content().string("\"" + UrlSafety.VALID.getValue() + "\"")); verify(linksService, times(1)).isSafeUrlByDirectSearch(url); }

post metodu
Post isteğine karşılık sonuç olarak döndürülen json'ı beklenen json ile karşılaştırmak için şöyle yaparız
@Test
void listFoods() {
  String expectedResponse = "...";
  mockMvc.perform(MockMvcRequestBuilders.post("/graphql")
    .content("{\"query\":\"{ foods { id name isGood } }\"}")
    .contentType(MediaType.APPLICATION_JSON)
    .accept(MediaType.APPLICATION_JSON))
    .andExpect(MockMvcResultMatchers.status().isOk())
    .andExpect(MockMvcResultMathers.content().json(expectedResponse))
    .andReturn();
}

20 Ekim 2020 Salı

SpringTest @DirtiesContext Anotasyonu

Giriş
Açıklaması şöyle. Eğer bir test ApplicationContext'i kirli bırakıyorsa kullanılabilir
There might be good reasons to use this annotation, e.g. when you modify the global application state in a test.

16 Mayıs 2020 Cumartesi

SpringTest @DynamicPropertySource Anotasyonu

Giriş
Açıklaması şöyle.
In contrast to the @TestPropertySource annotation that is applied at the class level, @DynamicPropertySource must be applied to a static method that accepts a single DynamicPropertyRegistry argument which is used to add name-value pairs to the Environment. Values are dynamic and provided via a Supplier which is only invoked when the property is resolved.
Örnek
Şöyle yaparız
@SpringBootTest
@Testcontainers
class ExampleIntegrationTests {

  @Container
  static Neo4jContainer<?> neo4j = new Neo4jContainer<>();

  @DynamicPropertySource
  static void neo4jProperties(DynamicPropertyRegistry registry) {
    registry.add("spring.data.neo4j.uri", neo4j::getBoltUrl);
  }

}

SpringTest @ContextConfiguration Anotasyonu - IntegrationTest İçindir

Giriş
Şu satırı dahil ederiz.
import org.springframework.test.context.ContextConfiguration;
Not : Bu anotasyon yerine daha gelişmiş olan @SpringJUnitConfig tercih edilebilir

Bu sınıf  spring dokümantasyonunda Integration Test için kullanılır deniliyor. Çünkü gerçek bir ApplicationContext ayağa kaldırılıyor. Testte @Autowired ApplicationContext yaparsak bu nesnenin dolu geldiğini görebiliriz. Böylece artık beanleri test etmek için  @MockBean,  @SpyBean kullanmaya gerek kalmıyor

Açıklaması şöyle
@ContextConfiguration annotation defines a class level metadata that is used to determine how to load and configure the ApplicationContext. @ContextConfiguration declares the application context resource locations or annotated classes used to load the context.
Yani bu anotasyon 
1. classes alanına verilen bean'leri ApplicationContext'e ekliyor. 
2. locations alanında verilen XMl'deki bean'leri ApplicationContext'e ekliyor.  
3. initializers alanına verilen bean'leri ApplicationContext'ten önce ilklendiriyor.

Eğer test kodunun bulunduğu src paketinde ikinci bir bean'i classes alanına yazmamışsam, otomatik olarak yüklenmiyor. @SpringBootTest ile karşılattırınca Integration Test içindir demek içimden gelmiyor :)

Açıklaması şöyle
If you are familiar with the Spring Test Framework, you may be used to using @ContextConfiguration(classes=…​) in order to specify which Spring @Configuration to load. Alternatively, you might have often used nested @Configuration classes within your test.

classes Alanı
Bu alanda src paketindeki gerçek bean'ler teker teker verilebilir veya @Configuration anotasyonuna sahip bean'ler verilebilir. İkinci kullanım daha pratik olabilir.

Örnek - Tek Bean
Şöyle yaparız.
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = MyBean.class)
class MyBeanTest {

  @MockBean
  EntityManager entityManager;

  @Autowired
  MyBean mybean;


  @Test
  void saveTest(){
    mybean.save();
    Mockito.verify(entityManager,Mockito.atLeastOnce()).merge.(Mockito.any());
  }
}
Örnek - @Configuration Anotasyonuna Sahip Bean
Elimizde şöyle bir kod olsun.
@Configuration
@ComponentScan(basePackages = "com.test.spring")
public class TestApplication {
}
TestApplication içinde bir bean'i test etmek için şöyle yaparız
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplication.class)
public class Test {
 ...
}
Örnek - - @Configuration Anotasyonuna Sahip Bean
Şöyle yaparız.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CacheableTest.CacheConfigurations.class)
public class CacheableTest {

  public static class Customer {
    ...
  }
  final public static AtomicInteger cacheableCalled = new AtomicInteger(0);
  final public static AtomicInteger cachePutCalled = new AtomicInteger(0);

  public static class CustomerCachedService {
    @Cacheable("CustomerCache")
    public Customer cacheable(String v) {
      cacheableCalled.incrementAndGet();
      return new Customer(v, "Cacheable " + v);
    }
    @CachePut("CustomerCache")
    public Customer cachePut(String b) {
      cachePutCalled.incrementAndGet();
      return new Customer(b, "Cache put " + b);
    }
  }
  @Configuration
  @EnableCaching()
  public static class CacheConfigurations {
    @Bean
    public CustomerCachedService customerCachedService() {
      return new CustomerCachedService();
    }
    @Bean
    public CacheManager cacheManager() {
      return new GuavaCacheManager("CustomerCache");
    }
  }
  @Autowired
  public CustomerCachedService cachedService;
  ...
}
Aynı sınıfta testleri şöyle yaparız.
@Test
public void testCacheable() {
  for(int i = 0; i < 1000; i++) {
    cachedService.cacheable("A");
  }
  Assert.assertEquals(cacheableCalled.get(), 1);
}

@Test
public void testCachePut() {
  for(int i = 0; i < 1000; i++) {
    cachedService.cachePut("B");
  }
  Assert.assertEquals(cachePutCalled.get(), 1000);
}
initializers Alanı
Spring context başlamadan önce çalışır. Test için kod çalıştırabilmeyi sağlar.
Örnek
Elimizde şöyle bir kod olsun. org.springframework.boot.test.util.TestPropertyValues
static class Initializer implements
  ApplicationContextInitializer<ConfigurableApplicationContext> {

  @Override
  public void initialize(ConfigurableApplicationContext configurableApplicationContext) {

    // initialize...
    TestPropertyValues
    //here you can add properties to connect...
    .of("some.property.key=some.property.value")
    .applyTo(configurableApplicationContext.getEnvironment());
  }
}
Şöyle yaparız.
@ContextConfiguration(initializers = Initializer.class)
locations Alanı
Yüklenecek bean'leri XML olarak belirtmeye yarar. value alanı ile aynıdır. String[] olarak tanımlanır.
Örnek
Şöyle yaparız.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext_test.xml" })
public class Test{
  @Autowired
  Foo foo;

  @Test
  public void checkOne(){
    System.out.println(foo.getBar());
  }
}