2010-12-17 83 views
1

我已經建立了一個服務如下:如何使用起訂量來模擬和測試IService

public interface IMyService 
{ 
     void AddCountry(string countryName); 
} 

public class MyService : IMyService 
{ 
     public void AddCountry(string countryName) 
     { 
      /* Code here that access repository and checks if country exists or not. 
      If exist, throw error or just execute. */ 
     } 
} 

test.cs中

[TestFixture] 
public class MyServiceTest 
{ 
    [Test] 
    public void Country_Can_Be_Added() 
    { } 

    [Test] 
    public void Duplicate_Country_Can_Not_Be_Added() 
    { } 

} 

如何測試AddCountry和MOQ庫或服務。我真的不確定在這裏做什麼或嘲笑什麼。有人可以幫我嗎?

框架我使用:

  1. NUnit的
  2. 起訂量
  3. ASP.NET MVC

回答

4

爲什麼你會需要使用起訂量?你不需要模擬IService。你的情況,你可以寫你的測試是這樣的:

[Test] 
public void Country_Can_Be_Added() 
{ 
    new MyService().AddCountry("xy"); 
} 

[Test] 
public void Duplicate_Country_Can_Not_Be_Added() 
{ 
    Assert.Throws<ArgumentException>(() => new MyService().AddCountry("yx")); 
} 

你會需要模擬IRepository,如果你有這樣一個場景:

interface IRepository { bool CanAdd(string country); } 
class MyService : IService 
{ 
    private IRepository _service; private List<string> _countries; 
    public IEnumerable<string> Countries { get { return _countries; } } 
    public X(IRepository service) { _service = service; _countries = new List<string>(); } 
    void AddCountry(string x) 
    { 
    if(_service.CanAdd(x)) { 
     _conntires.Add(x); 
    } 
    }  
} 

和測試這樣的:

[Test] 
public void Expect_AddCountryCall() 
{ 
    var canTadd = "USA"; 
    var canAdd = "Canadd-a"; 

    // mock setup 
    var mock = new Mock<IRepository>(); 
    mock.Setup(x => x.CanAdd(canTadd)).Returns(false); 
    mock.Setup(x => x.CanAdd(canAdd)).Returns(true); 

    var x = new X(mock.Object); 

    // check state of x 
    x.AddCountry(canTadd); 
    Assert.AreEqual(0, x.Countires.Count); 

    x.AddCountry(canAdd); 
    Assert.AreEqual(0, x.Countires.Count); 
    Assert.AreEqual(0, x.Countires.Count); 
    Assert.AreEqual(canAdd, x.Countires.First()); 

    // check if the repository methods were called 
    mock.Verify(x => x.CanAdd(canTadd)); 
    mock.Verify(x => x.CanAdd(canAdd)); 
} 
+0

我想我不得不嘲笑倉庫。 – 2010-12-17 18:02:50

+1

@Shawn Mclean - 你也可以將它存根。我認爲我已經看到了比嘲笑的庫更爲殘酷的庫測試。 – jfar 2010-12-17 18:15:24

+0

我建議使用Assert.Throws而不是ExpectedException。 – TrueWill 2010-12-17 18:25:10

3

您測試具體的MyService。如果它需要依賴(比如在IRepository上),你可以創建一個該接口的模擬並將其注入到服務中。正如所寫的,不需要模擬測試服務。

創建IMyService接口的意義在於測試依賴於MyService的其他類。一旦你知道知識庫的工作原理,當你測試MyService(你模擬或者存儲)時,你不需要測試它。一旦你知道MyService有效,當你測試MySomethingThatDependsOnMyService時,你不需要測試它。

+0

謝謝,這使得它更清晰。 – 2010-12-17 18:24:34