[Unit Test]Persistent Unit Test

持久層單元測試範例

Domain層

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
namespace App.Domain.Model
{
using System;

public class MemberInfo
{
public int MemberID { get; set; }

public string NickName { get; set; }

public string Email { get; set; }
}
}

namespace App.Domain.Repository
{
public interface IMemberInfoRepository
{
Tuple<Exception, MemberInfo> FindMemberInfo(int memberID);
}
}

Persistent層

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
namespace App.Persistent.SQL
{
public class MemberInfoRepository : IMemberInfoRepository
{
private string connectionString;

public MemberInfoRepository(string connectionString)
{
this.connectionString = connectionString;
}

public Tuple<Exception, MemberInfo> FindMemberInfo(int memberID)
{
try
{
using (var conn = new SqlConnection(this.connectionString))
{
var result = conn.QueryFirstOrDefault<MemberInfo>(
"SPName",
new
{
MemberID = memberID
},
commandType: CommandType.StoredProcedure);

return Tuple.Create<Exception, MemberInfo>(null, result);
}
}
catch (Exception ex)
{
return Tuple.Create<Exception, MemberInfo>(ex, null);
}
}
}
}

單元測試

  • 在AppLib下新增ConfigHelper
1
2
3
4
5
6
7
8
9
namespace App.Persistent.Tests.AppLib
{
internal static class ConfigHelper
{
public static readonly string MongoDBConnectionString = "mongodb://xxx.xxx.xx.xx:27017/";

public static string SQLConnectionString = @"Data Source=(localdb)\ProjectsV13;Initial Catalog=xxx;Integrated Security=True";
}
}
  • 新增單元測試

新增單元測試

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
namespace App.Persistent.Tests
{
[TestClass]
public class MemberInfoRepositoryTests
{
private IMemberInfoRepository memberInfoRepo;

[TestInitialize]
public void Initialize()
{
this.memberInfoRepo = new MemberInfoRepository(ConfigHelper.SQLConnectionString);
}

[TestMethod]
public void FindMemberInfo_Success_Test()
{
// Arrange
int memberID = 100000;

// Act
var result = this.memberInfoRepo.FindMemberInfo(memberID);

// Assert
Assert.IsNull(result.Item1);
Assert.IsNotNull(result.Item2);
Assert.AreEqual(memberID, result.Item2.MemberID);
}

[TestMethod]
public void FindMemberInfo_Exception_Test()
{
// Arrange
int memberID = 100000;

// Act
var result = this.memberInfoRepo.FindMemberInfo(memberID);

// Assert
Assert.IsNotNull(result.Item1);
Assert.IsNull(result.Item2);
}
}
}
-------------The End-------------