Java Test Commands

Published: 2019-08-04, Updated: 2023-03-19

Links

Mockito setar valor de variavel privada

Whitebox.setInternalState(Mockito.mock(Object.class), "uri", "myurl");

Mockito Verify

Validar se foi chamado n vezes

@Test
public void testDoFoo() {
  Bar bar = mock(Bar.class);
  BarFactory myFactory = new BarFactory() {
    public void createBar() { return bar;}
  };

  Foo foo = new Foo(myFactory);
  foo.foo();

  verify(bar, times(1)).someMethod();
}

Capturar parametros

ArgumentCaptor<Foo> firstFooCaptor = ArgumentCaptor.forClass(Foo.class);
ArgumentCaptor<Foo> secondFooCaptor = ArgumentCaptor.forClass(Foo.class);
verify(mockBar).doSomething(firstFooCaptor.capture());
verify(mockBar).doSomething(secondFooCaptor.capture());

// como pegar o resultado
firstFooCaptor.getValue();
firstFooCaptor.getAllValues();

Algumas funcionalidades utils para testes como

Proxyando as chamadas dos mocks no Mockito

long lastId = 0;
Mockito.doAnswer((InvocationOnMock invocationOnMock) -> {
	PaymentReleaseEntity entity = (PaymentReleaseEntity) invocationOnMock.getArguments()[0];
	entity.setId(++lastId);
	return null;
}).when(paymentReleaseDAO).save(Mockito.any(PaymentReleaseEntity.class));

Poder chamar varias vezes com varios retornos diferentes

@Test
public void diffentReturnsAtEveryCall() throws Exception {

	final BigInteger numberFive = Mockito.spy(new BigInteger("5"));
	Mockito.doReturn(1)
		.doReturn(2)
		.doReturn(3)
		.when(numberFive).intValue();
	
	Assert.assertEquals(1, numberFive.intValue());
	Assert.assertEquals(2, numberFive.intValue());
	Assert.assertEquals(3, numberFive.intValue());
}

Como criar pastas temporarias no JUnit

import java.io.File;
import java.io.IOException;
 
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
 
public class TestTemporaryFolderRule {
    @Rule
    public TemporaryFolder testFolder = new TemporaryFolder();
 
    @Test
    public void testInTempFolder() throws IOException {
        File tempFile = testFolder.newFile("file.txt");
        File tempFolder = testFolder.newFolder("folder");
        System.out.println("Test folder: " + testFolder.getRoot());
        // test...
    }
}

Verificar se eh mock

new MockUtil().isMock(mock(String.class)) // true
new MockUtil().isSpy(mock(String.class)) // false
new MockUtil().isSpy(spy(String.class)) // true
new MockUtil().isMock(spy(String.class)) // true
new MockUtil().isMock(new String()) // false
new MockUtil().isSpy(new String()) // false

Pegar lista de campos de uma classe com o Mockito

for (final InstanceField field : Fields.allDeclaredFieldsOf(jUnitInstance).instanceFields())
	System.out.println(field.read());

Resetar todos os mocks e spies de uma instancia

public void resetMocks(Object jUnitInstance){
	final MockUtil mockUtil = new MockUtil();
	for (final InstanceField field : Fields.allDeclaredFieldsOf(jUnitInstance).instanceFields()) {
		if(mockUtil.isMock(field.read())){
			Mockito.reset(field.read());
		}
	}
}

Usar mockito sem o RunWith no junit

@Rule public MockitoRule rule = MockitoJUnit.rule();
// ou no @Before coloque
MockitoAnnotations.initMocks(this);

Comparando JSON

Usando rest assured para comparação de json sem REST

public static void main(String[] args) {
  final var jsonPath = new io.restassured.path.json.JsonPath("""
    {
      "name":"grape"
    }
    """);
  assertEquals("grape", jsonPath.getString("name"));
}

Comparando JSON apenas comparando o padrao do id mas nao o valor

JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}", 
  new CustomComparator(
  JSONCompareMode.STRICT, 
  new Customization("entry.id", 
  new RegularExpressionValueMatcher<Object>("\\d"))));
 
JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}", 
  new CustomComparator(JSONCompareMode.STRICT, 
  new Customization("entry.id", 
  new RegularExpressionValueMatcher<Object>("\\d"))));

Strictnes

A partir do mockito 4.6.1, o @Mock também tem strictnes que antes era algo como WARN e agora estende o teste que é STRICT_STUBS, como mudar isso

//@MockitoSettings(strictness = Strictness.WARN)
@ExtendWith(MockitoExtension.class)
class SolverDockerTest {

  @Mock(strictness = Mock.Strictness.WARN)
  DockerService dockerService;


  // other example
  @Test
  void test(){
    lenient().doReturn(EntryTemplates.acmeAAAA())
      .when(this.solver)
      .findEntryTo(eq(wildcardHostName))
  }
  

........

Return null for all method calls except for one

doReturn(null)
  .when(this.solver)
  .findEntryTo(any())
;

doReturn(EntryTemplates.acmeAAAA())
  .when(this.solver)
  .findEntryTo(eq(wildcardHostName))
;

Comparando usando regex

JSONAssert.assertEquals(
  """
  {
    "id": "[\\\\w-]+",
    "watchSessionId": "[\\\\w-]+",
    "channelUri": "https://www.youtube.com/@Alizera",
    "viewers": 0,
    "liveUri": null,
    "channelId": "@Alizera",
    "platform": "Youtube",
    "createdAt": "^\\\\d{4}-([0][1-9]|1[0-2])-([0-2][1-9]|[1-3]0|3[01]).+",
    "occurrence": "NO_LIVE_FOUND"
  }
  """,
  """
  {
    "id": "fb72f4ed-fab4-4ffc-baa7-d2b9c75a038d",
    "watchSessionId": "679501f1-0a5a-4362-84d4-09d93261797b",
    "channelUri": "https://www.youtube.com/@Alizera",
    "viewers": 0,
    "liveUri": null,
    "channelId": "@Alizera",
    "platform": "Youtube",
    "createdAt": "2023-01-23T01:04:19.022958Z",
    "occurrence": "NO_LIVE_FOUND"
  }
  """,
  new CustomComparator(
      JSONCompareMode.STRICT,
      new Customization("***", new RegularExpressionValueMatcher<>())
  )
);

mockito commands, mockito bookmarks


FFMPEG COMMANDS ISOLATION nos Bancos de Dados

Comments