codingdojo kata 之fizzbuzz

一、背景

主要练习TDD,测试驱动开发。开发之前先写测试,将预期结果写入,测试是否达到预期。为代码重构提供便利。

二、题目

该题取自编码道场。http://codingdojo.org/kata/FizzBuzz/

三、实现

1、单元测试

package com.kata.fizzbuzz;

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class FizzBuzzParameTest {

	private FizzBuzz fz = new FizzBuzz();
	
	private int input1;
	private String expected;
	@Parameters
	public static Collection t(){
		return Arrays.asList(new Object[][]{
				{3,"Fizz"},
				{4,"4"},
				{90,"Fizz-Buzz"}

		});
	}
	
	public FizzBuzzParameTest(int input1,String expected) {
		this.input1 = input1;
		this.expected = expected;
	}

	@Test
	public void test() {
		assertEquals(expected, fz.FizzOrBuzz(input1));
	}

}

2、功能代码

package com.kata.fizzbuzz;

public class FizzBuzz {

	public String FizzOrBuzz(int i) {
		String returns = "";
		if(i%15 == 0){
			returns = "Fizz-Buzz";
		}else if (i % 3 == 0) {
			returns = "Fizz";
		}else if (i % 5 == 0) {
			returns = "Buzz";			
		}else {
			returns = Integer.toString(i);
		}
		return returns;
	}

}

四、运行单元测试

codingdojo kata 之fizzbuzz_第1张图片

你可能感兴趣的:(JAVA)