我是新來的合同,我從概述中瞭解到它可以幫助您在編譯時發現合同違規。如何獲得編譯時合同警告/錯誤
當我有明確違反合同的代碼時,我沒有收到編譯時警告或錯誤。
我希望在測試中設置Person.Name = null
的代碼行會給我一個警告或錯誤,因爲它違反了合同。
如何調整我的代碼以獲取編譯時間消息?
說明:爲了澄清,我把它放在單元測試中的唯一原因是得到編譯時間消息。測試本身目前通過,這是一個運行時間方面;我想它應該通過,因爲它是編譯時測試而不是運行時測試。無論如何,問題是關於編譯時間消息還是缺乏,而不是關於單元測試結果。被測
代碼:
using System;
using System.Diagnostics.Contracts;
namespace DomainModel
{
[ContractClass(typeof(IPersonContract))]
public interface IPerson
{
string Name { get; set; }
}
[ContractClassFor(typeof(IPerson))]
public abstract class IPersonContract : IPerson
{
private IPersonContract() { }
string IPerson.Name
{
get
{
throw new NotImplementedException();
}
set
{
Contract.Ensures(!string.IsNullOrEmpty(value));
}
}
}
}
這裏是我的測試:
using Moq;
using NUnit.Framework;
using DomainModel;
namespace Unit
{
/// <summary>
/// A test class for IPerson
/// </summary>
[TestFixture()]
public class IPersonShould
{
#region "Unit Tests"
[Test()]
public void ThrowWhenIPersonIsGivenEmptyName()
{
//set up
IPerson IPerson = this.Person;
string expectedResult = null;
//Dim NameParam1 as String = Nothing
Person.Name = null; // Would expect this line to generate warning or error
//perform test
string actualResult = IPerson.Name;
//compare results
Assert.AreEqual(expectedResult, actualResult);
}
#endregion
#region "Setup and Tear down"
private class MyPerson : IPerson {
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
private MyPerson Person;
/// <summary>
/// This runs only once at the beginning of all tests and is used for all tests in the
/// class.
/// </summary>
[TestFixtureSetUp()]
public void InitialSetup()
{
Person = new MyPerson();
}
/// <summary>
/// This runs only once at the end of all tests and is used for all tests in the class.
/// </summary>
[TestFixtureTearDown()]
public void FinalTearDown()
{
}
/// <summary>
/// This setup function runs before each test method
/// </summary>
[SetUp()]
public void SetupForEachTest()
{
}
/// <summary>
/// This setup function runs after each test method
/// </summary>
[TearDown()]
public void TearDownForEachTest()
{
}
#endregion
}
}
這裏是我的當前設置:
我不再有這個項目。我無法去嘗試一下,看看這個答案是否解決了這個問題。你可以用我的代碼設置一個項目,並在你的答案被應用後給出編譯器警告的屏幕截圖嗎?我很抱歉要你這樣做。 – toddmo 2016-03-03 19:22:01