鼎鼎知识库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

02使用xUnit进行TDD测试驱动开发.md 1.6KB

3 yıl önce
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 使用`TDD`方式。
  2. ```
  3. public class MyPrimeService
  4. {
  5. public bool IsPrime(int num)
  6. {
  7. throw new NotImplementedException("not implemented");
  8. }
  9. }
  10. ```
  11. 单元测试
  12. ```
  13. [Fact]
  14. public void IsPrime_InputIs1_ReturnFalse()
  15. {
  16. //Arrange
  17. var primeService = new MyPrimeService();
  18. //Act
  19. bool result = primeService.IsPrime(1);
  20. //Assert
  21. Assert.False(result, "1 should not be prime");
  22. }
  23. ```
  24. 修改代码让单元测试通过。
  25. ```
  26. public bool IsPrime(int num)
  27. {
  28. if(num==1)
  29. {
  30. return false;
  31. }
  32. throw new NotImplementedException("not implemented");
  33. }
  34. ```
  35. 目前单元测试输入条件有限,输入更多条件。
  36. ```
  37. [Theory]
  38. [InlineData(-1)]
  39. [InlineData(0)]
  40. [InlineData(1)]
  41. public void IsPrime_ValueLessThanTwo_ReturnFalse(int value)
  42. {
  43. //Arrange
  44. var primeService = new PrimeService.MyPrimeService();
  45. //Act
  46. var restul = primeService.IsPrime(value);
  47. //Assert
  48. Assert.False(restul, $"{value} should not be prime");
  49. }
  50. ```
  51. 有两个不通过
  52. ```
  53. 失败! - Failed: 2, Passed: 1, Skipped: 0, Total: 3, Duration: 4 ms
  54. ```
  55. 其实所有都不应该通过。修改代码:
  56. ```
  57. public bool IsPrime(int num)
  58. {
  59. if(num < 2)
  60. {
  61. return false;
  62. }
  63. throw new NotImplementedException("not implemented");
  64. }
  65. ```