Unit Testing, Clean code and more …(Part 1)

What is clean code?

Clean code is code that is easy to read, understand, maintain and extend.

What has tests got to do with clean code?

Test Pyramid

Image credit: https://martinfowler.com/bliki/TestPyramid.html

Unit Tests

Based on context, a unit could be a class, a method/function, a module or even a group of classes. So, if a unit does not have a fixed definition, how do I decide what the test should do? What are the characteristics of a good unit test?

Ways of Testing the unit

Image credit: https://martinfowler.com/bliki/UnitTest.html
public class User {
private final String name;
private final Wallet wallet;
public User(String name, Wallet wallet){
this.name = name;
this.wallet = wallet;
}
public boolean hasMoney() {
return ! wallet.isEmpty();
}
}
//Testclass UserTest {@Test
void shouldNotHaveAnyMoneyWhenCreatedWithEmptyWallet(){
User joe = new User("Joe", Wallet.withNoMoney());
assertFalse(joe.hasMoney());
}
@Test
void shouldHaveMoneyWhenCreatedWithNonEmptyWallet(){
Wallet walletWithMoney = WalletBuilder.withValue(20.0).build();
User joe = new User("Joe", walletWithMoney);
assertTrue(joe.hasMoney());
}
}
public class Wallet {
private static final String DEFAULT_CURRENCY = “INR”;
private Money money;

static Wallet withNoMoney() {
return new Wallet();
}
private Wallet(){
this(new Money(DEFAULT_CURRENCY, 0.0))
}
public Wallet(Money money) {
this.money = money;
}
boolean isEmpty() {
return money == null || money.getValue == 0;
}
}
//Testclass WalletTest { @Test
void shouldTestThatWalletIsEmpty() {
Wallet wallet = new Wallet();
assertTrue(wallet.isEmpty());
}
}

Solitary Tests

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store