Skip to content

Instantly share code, notes, and snippets.

@uzilan
Last active April 4, 2023 10:49
Show Gist options
  • Save uzilan/c985e309afafdb388dbac24e187e53d4 to your computer and use it in GitHub Desktop.
Save uzilan/c985e309afafdb388dbac24e187e53d4 to your computer and use it in GitHub Desktop.
Demo PR
package com.example.demo;
import org.springframework.lang.NonNull;
import java.util.UUID;
public class Account {
private final UUID id;
private final String name;
public Account(@NonNull final UUID id, final String name) {
this.id = id;
this.name = name;
}
@NonNull
public UUID getId() {
return id;
}
public String getName() {
return name;
}
}
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
@Controller()
@RequestMapping("/accounts")
public class AccountController {
@Autowired
AccountDao dao;
public AccountController(AccountDao dao) {
this.dao = dao;
}
// get all accounts
@GetMapping
public List<Account> accounts() {
return dao.getAllAccounts();
}
// get all account names
@GetMapping
public List<String> accountNames() {
return dao.getAllAccounts().stream()
.map(Account::getName)
.map(String::toUpperCase)
.collect(toList());
}
// get all accounts
@PostMapping
public Account createAccount(Account account) {
return dao.createAccount(account);
}
}
package com.example.demo;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class AccountControllerTest {
@Test
public void getAccountName() throws NoSuchFieldException, IllegalAccessException {
Account a = new Account(UUID.randomUUID(), "Bosse");
Field privateField = Account.class.getDeclaredField("name");
privateField.setAccessible(true);
String name = (String)privateField.get(a);
assertEquals("Bosse", name);
}
@Test
public void testGetAccountNames() throws Exception {
Account mockAccount = mock(Account.class);
UUID rand = UUID.randomUUID();
when(mockAccount.getName()).thenReturn("Bosse");
when(mockAccount.getId()).thenReturn(rand);
AccountDao accountDaoMock = mock(AccountDao.class);
when(accountDaoMock.getAccountById(rand)).thenReturn(mockAccount);
String result = accountDaoMock.getUserNameById(1);
// verify the result
assertEquals("Bosse", result);
}
}
@uzilan
Copy link
Author

uzilan commented Apr 4, 2023

some comment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment