MVC in asp.net

sundar k replied to Naveen Kumar at 22-Feb-07 12:12

check out the below second link , it can help you in creating layered approach!

Implementing MVC Design Pattern in .NET

http://www.c-sharpcorner.com/UploadFile/napanchal/MVCDesign12052005035152AM/MVCDesign.aspx


MVC architecture in ASP.Net using C# and Microsoft Data Access Application block

http://www.dotnetheaven.com/Uploadfile/munnamax/mvcarchitecture03282006231811PM/mvcarchitecture.aspx

and just one more fyi,

http://www.dotmugs.ch/member/download.ashx?t=~/events/aspnetmvc/aspnetmvc_slides.pdf

how to create the folder structure for Asp.net,C# project in 2.0 using MVC architecture - Naveen Kumar  22-Feb-07 7:33:22 AM
      Here is a good sample project - Robert Stanton  22-Feb-07 8:40:01 AM
      MVC in asp.net - sundar k  22-Feb-07 12:12:24 PM
      Don't forget to keep it simple... - Sean Patterson  22-Feb-07 4:37:56 PM
          Thanks everyone for the information. - Naveen Kumar  22-Feb-07 11:07:47 PM


WRITTEN BY
hopangbear

트랙백  0 , 댓글  0개가 달렸습니다.
secret

Web Developement : http://msdn.microsoft.com/en-us/library/aa155073.aspx 

Microsoft patterns and practices : http://msdn.microsoft.com/en-us/library/ms998572.aspx

참고할 것 !


WRITTEN BY
hopangbear

트랙백  0 , 댓글  0개가 달렸습니다.
secret
ASP.NET 1.1의 Page Life Cycle


1. Initialization : OnInit 메소드
2. View State 로드 : LoadViewState 로드
3. 포스트백 된 데이터로 처리 : LoadpostData 메소드
4. Load : OnLoad 메소드
5. 각 컨트롤의 포스트백 Event 처리 : OnClick 이벤트
6. Prerender : OnPreRender 메소드
7. View State 저장 : SaveViewState 메소드
8. Render : Render 메소드
9. Dispose : Dispose 메소드




ASP.NET 2.0의 Page Life Cycle

1. Page.AddParsedSubObject
2. Page.CreateControlCollection
3. Page.AddedControl
4. Page.ResolveAdabter
5. Pge.DeterminePostBackMode
6. Page.PreInit
7. WebControl.ResolveAdapter
8. Webcontrol.Init
9. WebControl.TrackViewState
10. Page.Init
11. Page.TrackViewState
12. Page.InitComplete
13. Page.LoadPageStateFromPersistenceMedium
14. WebControl.LoadViewState
15. Page.PreLoad
16. Page.Load
17. WebContol.Load
18. WebControl.OnClick
19. Page.LoadComplete
20. Page.PreRender
21. WebControl.PreRender
22. Page.PreRenderComplete
23. Page.SaveViewState
24. WeControl.SaveViewState
25. Page.Save.ViewState
26. Page.SavePageStateToPersistenceMedium
27. Page.SaveStateComplete
28. Page.CreateHtmlTextWriter
29. Page.Render
30. Page.RenderChildern
31. WebControl.RenderControl
32. Page.CreateHtmlTextWriter
33. WebControl.UnLoad
34. WebControl.Dispose
35. Page.Unload
36. Page.Dispose

ASP.NET 2.0 뭔 이벤트가 이리 많아졌냐..;;

WRITTEN BY
hopangbear

트랙백  0 , 댓글  1개가 달렸습니다.
  1. 지금은 반짝반짝 빛이 나겠지,, 하지만 시간이 흐르면 그빛은 사라저버릴거야,지금 우리처럼
secret

마소1(마이크로소프트웨어)에 C# 어플리케이션의 성능향상 기사를 쓸 때 참고했던 자료를 정리해봤다. 안타깝지만 일부 자료는 웹에 공개되어 있지 않아서 소개할 수 없었다. 되도록 추천글부터 나열하려고 했지만, 기억이 가물가물해서 정리하는데 애먹었다.

문자열 성능 향상

XML 직렬화

가비지 콜렉터

어플리케이션 성능 향상


UPDATED 2006.12.12 Jeffrey Richter의 주옥 같은 Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework를 한글로 번역하신 분이 계십니다. 이 글의 존재를 소개해주신 분은 ANSYS20님입니다. 두 분에게 박수를! 짝짝짝!


WRITTEN BY
hopangbear

트랙백  0 , 댓글  2개가 달렸습니다.
  1. 희미한 달빛이 샘물 위에 떠있으면,나는 너를 생각한다.
  2. 당신은 내가사랑할 만한 사람이 아니예요,사랑하지 않으면 안될 사람이예요.
secret
 

ASP.NET 2.0 의 배포 방법

 

ASP.NET 2.0 으로 웹 사이트를 만들고 난 후 실제 웹 서버에 배포 하는 방법은 여러 가지가 있다.

 

1. ASP.NET 1.x 환경의 배포

기본적으로 기존 1.x 버전에서는 Visual Studio 에서 웹 사이트 빌드를 하게 되면 코드 비하인드 파일들을 묶어서 하나의 DLL 로 내 뱉었다.

결국 웹 서버에 다음과 같은 파일들을 저장하게 된다. (config 등의 설정파일은 제외)

-          aspx 파일들

-          bin 폴더의 dll 파일

 

결국 aspx 파일은 최초 사용자의 요청 시 cs 파일의 내용과 연관되는 컴파일 과정을 거치게 된다.

 

2. ASP.NET 2.0 환경의 배포

2.0 에서는 Pre-Complication 을 지원한다. , 완전히 컴파일 해서 dll 만 웹 서버에 배포하는 방식이다.

이렇게 하면 최초 요청자 마저 컴파일 시간을 기다릴 필요가 없게 되는 것이다

 

이외에도 2.0 에서는 다양한 형태로 배포를 할 수 있도록 지원하는데 하나씩 살펴 보자.

 

2.1 웹 사이트 복사

가장 단순한 형태의 배포에 해당한다.
모든 파일(cs 파일 포함)을 웹 서버로 복사하는 방법이다.

VS 상단 메뉴의 웹 사이트 -> 웹 사이트 복사를 선택하거나 프로젝트 우 클릭 후 웹 사이트 복사 항목을 선택하면 아래와 같은 파일을 전송할 수 있는 화면이 나온다.

여기서 로컬 폴더나 네트워크 드라이버, ftp, http 로 파일들을 전송하면 된다.


, 한가지 생각해 보아야 할 것은 cs 파일을 웹 서버에 배포를 할 것인가에 대한 보안적인 측면을 고려해 보아야 할 것이다.





2.2 웹 사이트 게시

미리 컴파일 된 형태로 배포를 하고 싶을 경우 웹 사이트 게시를 이용하면 된다.

상단 메뉴에 빌드 -> 웹 사이트 게시메뉴나 프로젝트 우 클릭으로 웹 사이트 게시를 선택하면 아래와 같은 게시 옵션 창이 뜬다.

 

옵션에서 기준이 되는 것은 aspx 파일 분리 유/컴파일 되는 범위이다.

 

1) 미리 컴파일 된 이 사이트를 업데이트 할 수 있도록 허용

이 항목은 aspx 파일은 업데이트가 가능하도록 소스를 남겨두겠냐는 옵션이다

이 옵션이 체크되면, 1.x 때와 유사하게 cs 파일들은 컴파일 되어서 dll 로 만들어 지고 aspx 파일들은

여전히 남게 되어 웹 서버에 aspx 파일들과 dll 파일을 배포하면 된다.

업데이트 할 수 있도록 허용이라는 말을 풀이해 보면 aspx 파일의 소스가 유지되도록 하여 향후 수정

할 수 있도록 한다고 할 수 있겠다

 

2) 고정된 이름을 사용하고 페이지당 하나의 어셈블리만 만들기

   1) 의 과정에서 생기는 dll 파일은 해당 프로젝트의 모든 cs 파일을 단일 dll 로 컴파일 하는데 반해,

   이 옵션이 선택되면, 페이지 하나당 하나의 dll 이 생긴다. 즉 페이지 수만큼 dll 이 생기는 것이다

   이렇게 배포를 하면 특정 cs 파일 하나만 업데이트 할 경우 해당하는 dll 만 업데이트 하면 되므로 유지/

   보수성이 좋아 질 수 있다. 또한 컴파일 되어 생성된 어셈블리 이름은 파일이름을 그대로 포함한 형태가

   된다.

  

마지막 옵션은 컴파일된 어셈블리에 강력한 이름을 부여하는 옵션으로 자세한 사용 빈도가 그리 크지 않으므로 설명은 생략하도록 한다

 

결국 1) 2) 의 옵션 조합으로 배포를 할 수 있게 되는데 이 둘을 조합하게 되면 두 옵션의 조합으로써 말로 풀어 써 본다면, Aspx 는 별도로 두고 (dll 에 포함시키지 않으면서 페이지 당 컴파일된 어셈블리(dll) 하나 씩 생성되는 것이다.

 

다음 그림은 웹 사이트 게시를 선택했을 때 나타나는 속성 창이다


2.2.1 옵션 조합 별 생성 파일 예시

웹 프로젝트에 다음과 같이 3개의 페이지가 있다고 가정하고 옵션을 조정해 가며 결과물을 보자.

- Default.aspx, Default.2aspx, Default.3aspx

 

1) 미리 컴파일 된 이 사이트를 업데이트 할 수 있도록 허용 만 체크

Aspx 파일은 수정 가능하도록 남겨두고 모든 cs 파일은 단일 어셈블리로 컴파일 하도록 한다

, aspx 파일의 소스는 그대로 남아 있게 된다. (1.x 때의 배포와 동일한다)



Bin 폴더 :

 

2) 고정된 이름을 사용하고 페이지당 하나의 어셈블리만 만들기 만 체크

Aspx 파일은 cs 파일과 같이 컴파일 되고 페이지 별로 컴파일 하도록 한다


Bin 폴더 :


이 경우 aspx 파일은 cs 와 같이 컴파일 된다.

그러나 여전히 aspx 파일들은 남아있기는 하지만, aspx 파일을 열어 보면 소스는 없어지고 다음과 같은 메시지만 존재한다.

이 마커 파일은 미리 컴파일 도구에서 생성한 것으로서 삭제하면 안 됩니다.’

즉 운용을 위해서만 존재할 뿐 소스는 모두 없어졌다는 말이 된다.

 

또한 각 페이지별로 컴파일이 되어 페이지 당 1개의 dll 이 생성되었음을 알 수 있다

 

3) 두 옵션 모두 체크

Aspx 파일을 수정 가능하도록 남겨두고 cs 파일은 페이지 별로 컴파일 하도록 한다.


Bin 폴더:


이 경우에는 aspx 파일을 열어 보면 소스가 그대로 남아 있다

 

4) 두 옵션 모두 해제한 경우.

이렇게 하면 모든 aspx파일과 cs 파일은 단일 어셈블리로 컴파일 되도록 하는 것이 된다.

이렇게 하면 웹 사이트의 모든 소스를 숨길 수 있게 된다.

   

 

* 결론

지금 까지 살펴 본 대로, ASP.NET 2.0 에서는 다양한 형태의 배포 모델을 지원한다.

서비스의 성격 및 유지보수성 등을 고려하여 적절한 배포 방법을 선택하는 것이 좋을 것 이다.

, 현재의 배포환경 및 제약조건뿐만 아니라 향후 유지/보수성 및 확장성을 고려하여 적절한 배포 방법을 선택해야 할 것이다.

 

 

다음의 msdn 에서는 웹 게시와 관련된 상세한 내용을 담고 있습니다.

꼭 한번 읽어보기를 강추 합니다~~

참고 url : http://www.microsoft.com/korea/msdn/library/ko-kr/dnaspp/html/aspnet_merge_exe.aspx

[출처] http://mkexdev.net/Article/Content.aspx?parentCategoryID=1&categoryID=11&ID=251


WRITTEN BY
hopangbear

트랙백  0 , 댓글  0개가 달렸습니다.
secret
VSTS 2008에서의 WebService Unit Test는 다음과 같이 진행한다.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting.Web;
using TestProject1.localhost;

[TestMethod]
[AspNetDevelopmentServer("HelloWorldServer", @"C:\Documents and Settings\user\My Documents\Visual Studio 2005\WebSites\WebSite1")]
public void HelloWorldTest()
{
     HelloWorldService target = new HelloWorldService();

     Assert.IsTrue( WebServiceHelper.TryUrlRedirection
                         (
                          target,
                          testContextInstance,
                          "HelloWorldServer"
                         ),
                   "Web service redirection failed."
                   );

     string expected = "Hello World";
     string actual;

     actual = target.HelloWorld();

     Assert.AreEqual(
                     expected,
                     actual,
                     "TestProject1.localhost.HelloWorldService.HelloWorld did not return the expected value."
                     );
}


AspNetDevelopmentServer 구문의 경우 자동으로 생성되지 않으므로 직접 기입
Assert.IsTrue 구문의 경우 계속 에러가 나서 Skip-_-;



WRITTEN BY
hopangbear

트랙백  0 , 댓글  1개가 달렸습니다.
  1. 당신 매력있어, 자기가 얼마나 매력있는지 모르는게 당신매력이야
secret
http://ibatis.apache.org/dotnetdownloads.cgi

http://schoolspan.springnote.com/pages/127681

http://2005elc.elancer.co.kr/eTimes/page/eTimes_list.html?cstr=Q0FURUNPREU9QTAzMDQwMjAw

http://blog.naver.com/piljae77?Redirect=Log&logNo=120047853827

WRITTEN BY
hopangbear

트랙백  0 , 댓글  0개가 달렸습니다.
secret
 It looks like Office 2003 .Net programmability support is not installed.  You need to modify your installed version of Office and install this option.  I thought we had a better error message for this...

1.  In Add/Remove programs, locate your Office application and select it.

2.  Click on the 'Change' button

3.  Select 'Add or Remove features' and click 'next'

4.  Select 'Choose advanced customization of applications' and click 'next'

5.  In the tree view, expand 'Microsoft Office Excel' and make sure the .NET Programmability Support option is set to 'run from my computer'.

6.  Click 'update'.

역시 MS -_-; 에러메시지만 덩그러니 보여주고... 재설치하란다... 세번은 한거 같은데 결국 안되서
이래저래 삽질하다 찾은 해결책....

TFS & Excel 연동시 참고하세요!


WRITTEN BY
hopangbear

트랙백  0 , 댓글  2개가 달렸습니다.
  1. interesting! its great, I love this article very much including me and my friends very much because i got my desired information in your posting. keep it up and continue your work
  2. 당신 매력있어, 자기가 얼마나 매력있는지 모르는게 당신매력이야
secret

이 글에서는 한 대의 컴퓨터에 Visual Studio Team System 2008의 모든 구성 요소를 설치하려 할 때의 설치 순서에 대해 설명합니다.


VSTS 2008을 구성하는 구성 요소에는 여러 가지가 있습니다.

IIS, SQL Server, Team Foundation Server, 4개의 Edition, TFS 클라이언트, Power Tool 등...


이러한 VSTS 2008 구성 요소를 설치하기 위한 순서는 다음과 같습니다.


1. Windows Server 2003 SP1
2. MS Office Excel/Project 2007
3. IIS 6.0 (with ASP.NET) - Windows Server 2003 CD 필요
4. SQL Server 2005
5. SQL Server 2005 SP1 또는 SP2
6. Team Foundation Server 2008 (with Windows SharePoint Services 3.0)
   (http://www.microsoft.com/downloads/details.aspx?displaylang=ko&FamilyID=b0155166-b0a3-436e-ac95-37d7e39a440c)
7. Team Foundation Build Server (선택)
8. VSTS 2008 팀 탐색기
   (http://www.microsoft.com/downloads/details.aspx?displaylang=ko&FamilyID=0ed12659-3d41-4420-bbb0-a46e51bfca86)
9. Visual Studio Team Suite 2008

   - Architecture Edition, Development Edition, Test Edition, Database Edition 포함
   (http://www.microsoft.com/downloads/details.aspx?displaylang=ko&FamilyID=d95598d7-aa6e-4f24-82e3-81570c5384cb)
10. Visual Studio Team System Web Access 2008 Power Tool
   - 웹 기반의 TFS 클라이언트
   (http://www.microsoft.com/downloads/details.aspx?displaylang=ko&FamilyID=c568fba9-3a62-4781-83c6-fdfe79750207)
11. VSTS 2008 Team Foundation Server Power Tools
   - Process Template Editor, Work Item Templates, Custom check-in polices 등

  (http://www.microsoft.com/downloads/details.aspx?FamilyID=7574836f-4a0b-454f-a340-85da4698177c&DisplayLang=en)


이 중 Team Foundation Server 설치와 관련된 1 ~ 6은 여기에서 확인하세요.


감사합니다.


WRITTEN BY
hopangbear

트랙백  0 , 댓글  0개가 달렸습니다.
secret

1. Introduction

This document will cover practical approach to White box Testing Techniques using Microsoft Visual Studio 2005 Test Team Suite.  It covers concepts with a simple, easy to follow example.

As Microsoft Visual Studio 2005 Test Team Suite is new to the market, there is not enough and useful documentation for testing. So we are sharing our experience in this paper.

2. Topics Covered

  • White box Testing concepts,
  • Types and techniques,
  • Basics and benefits of Unit testing
  • Tool overview Microsoft Visual Studio 2005,
  • Features of MSVSTS 2005
  • Hands-on on Unit Testing features of MSVS 2005
  • Best Practices
  • Conclusion

3. What is White box testing?

White box testing is a technique for Unit Testing used to validate that a particular module of source code is working properly. The idea is to write test cases for all functions and methods so that whenever a change causes a regression, it can be quickly identified and fixed. Ideally, each test case is separate from the others. This type of testing is mostly done by the developers and not by end-users.

  • A.K.A. "Glass Box testing" or "Structural testing" or "Clear Box Testing"
  • Focuses on Lines of Code
  • Looks at specific conditions
  • Looks at the mechanics of the Application
  • Useful in the early stages of testing.

4. Benefits

The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. Unit testing provides a strict, written contract that the piece of code must satisfy. As a result, it affords several benefits.

4.1. Cheaper cost
There is not additional cost for Team Test Suite. It is a component that comes along with the MS Visual Studio IDE.

4.2. Disciplined Development
Well defined deliverable for the developer and more quantifiable progress. Often, just considering a test case will identify issues with an approach/design.

4.3. Facilitates change and Reduces code fragility
Unit testing allows the programmer to refractor code at a later date, and make sure the module still works correctly (i.e. regression testing).

4.4. Simplifies integration
Unit testing helps eliminate uncertainty in the pieces themselves and can be used in a bottom-up testing style approach. By testing the parts of a program first and then testing the sum of its parts, integration testing becomes much easier.

4.5. Documentation
Unit testing provides a sort of "living document". Clients and other developers looking to learn how to use the class can look at the unit tests to determine how to use the class to fit their needs and gain a basic understanding of the API.

4.6. Relative cost to fix defects graph

A high percentage of errors are caught in the review process:
According to Fagan (1976) 67%,
Jones (1977) 85%
The earlier an error is caught the cheaper it is to fix.

5. White Box Testing Techniques Types

BS7925-2 lists all the white box test techniques

  • Statement Testing
  • Branch / Decision Testing
  • Branch Condition Testing
  • Branch Condition Combination Testing
  • Modified Condition Decision Testing
  • Linear Code Sequence & Jump
  • Data Flow Testing
  • Cyclometric Complexity Technique

5.1. Why do we need White Box techniques?

  • Provide formal structure to testing code
  • Enable us to measure how much of a component has been tested

5.2. Systematic techniques exist white box testing:

  • Give us a systematic approach to testing
  • Test cases are developed in a logical manner
  • Enable us to have a sub-set of tests that have a high probability of finding faults
  • By using defined techniques we should be able to produce corresponding measurements, Means we can see how testing is progressing

5.3. Designing test cases:

To plan and design effective cases requires a knowledge of the

  • Programming language used
  • Databases used
  • Operating system(s) used
  • And ideally knowledge of the code itself

6. Types

6.1. Statement Testing

  • "A test case design technique for a component in which test cases are designed to execute statements"
  • Test cases are designed and run with the intention of executing every statement in a component
  • Statement Testing example:
    a;
    if (b)
      {
      c;
      }
    d;

Any test case with b TRUE will achieve full statement coverage

NOTE: Full statement coverage can be achieved without exercising with b FALSE

6.2. Branch / Decision testing

  • A technique used to execute all branches the code may take based on decisions made.
  • Test Cases designed to ensure all branches & decision points are covered

Branch / Decision testing example

a;
if (b)
  {
  c;
  }
d;

Note: 100% statement coverage requires 1 test case (b = True)
          100% branch / decision coverage requires 2 test cases: (b = True & b = False)

6.3. Cyclometric Complexity Technique:

A quantitative measure of the logical complexity of a program.

There are three algorithms for its calculation.

V(G) = E - N + 2
V(G) = Np + 1
V(G) = R
V(G) = the cyclometric complexity
N = Number of flow graph nodes
Np =  Number of flow graph predicate nodes
E = Number of flow graph edges
R = Number of flow graph regions

Example:
void Sort(int items[],int toPos)
{ int pos = 0, minPos = 1;

/* iterate over the vector */
1 while( pos < toPos ) {
2 minPos = pos + 1;

 /* find the smallest item */
3 while( minPos <= toPos ) {
4  if(items[pos] < items[minPos]){ /* swap items */
5  int temp = items[pos];
6  items[pos] = items[minPos];
7           items[minPos] = temp;
8 } /*end if*/
9 minPos++;
10 } /*end while inner loop */
11 pos++;
12 } /*end while outer loop */
 }

V(G)= Cyclometric complexity
N = Number of flow graph nodes =7
Np = Number of flow graph predicate nodes =3
A predicate node represents a point where flow may continue on two or more paths.
E = Number of flow graph edges =9
R = Number of flow graph regions =4

V(G) = E - N + 2 = 9 - 7 + 2 = 4
V(G) = Np + 1 = 3 + 1 = 4
V(G) = R = 4
I.E. V(G) = 4

Flow Graph

7. Microsoft Visual Studio 2005 Overview

MSVS 2005 is an expansion of Visual Studio Professional including support for various roles in the development process.

Product goals:

  • Facilitate better team communication
  • Integrate tools:
    Team System Suite used for Testing is an add-on component of Visual Studio IDE.
  • Improve reporting and tracking
  • Establish and enforce process
  • Enable customization and extensibility

7.1. Architecture

 

7.2. What is Team Test Suite?

With the latest release of Visual Studio Test System (VSTS) comes a full suite of functionality for Visual Studio Team Test (TT).

Team Test is a Visual Studio integrated unit-testing framework that enables:

  • Code generation of test method stubs.
  • Running tests within the IDE.
  • Incorporation of test data loaded from a database.
  • Code coverage analysis once the tests have run.

In addition, Team Test includes a suite of testing capabilities not only for the developer, but the test engineer as well. E.g.: Manual testing

8. Hands-on Approach

In this section, we are going to walk through how to create Team Test unit tests. We begin by creating a sample VB project, and then generating the unit tests for methods within that project. This will provide readers new to Team Test and unit testing with the basic syntax and code. It also provides a good introduction on how to quickly set up the test project structure.
One of the key features of Team Test is the ability to load test data from a database and then use that data within the test methods. After demonstrating basic unit testing, we describe how to create test data and incorporate it into a test.

8.1. Pre Requisites

  • Visual Studio 2005 Team Suite Version 8.0
  • Microsoft .NET Framework Version 2.0
  • MS SQL Server 2005

8.2. Steps involved

1. Open Visual Studio IDE
Click Start-->Programs-->Microsoft Visual Studio 2005-->Microsoft Visual Studio 2005

2. Creating a Sample VB Project
File-->New Project-->Chose from Templates as below

 

3. Add a simple "add" method to the code. This method accepts 2 arguments, adds them and returns the total.

 

4. Create Unit Test for "add" method by right clicking on the method


5. This will display a dialog box for generating unit tests into a different project (see Figure below). By default, the Output project setting is for a new Visual Basic project, but C# and C++ test projects are also available. For this article, we will select as Visual Basic project click the OK button.

6. 


 

7. Now enter a Test project name of VSTSVBDemo.Test for the project name.

 

8. The generated test project contains following files related to testing.

File Name Purpose
AuthoringTest.txt Provides notes about authoring tests including instructions on adding additional tests to the project.
sampleTest.vb Includes generated test for testing the add(x,y) method along with methods for test initialization and cleanup.

9. In addition to some default files; the generated test project contains references to both the Microsoft.VisualStudio.QualityTools.UnitTestFramework and the SampleVB project, which the unit tests are executing against. The former is the testing framework assembly the test engine depends on when executing the unit tests. The latter is a project reference to the target assembly we are testing.

 

There are two important attributes related to testing with Team Test.

First, the designation of a method as a test is through the TestMethodAttribute attribute. In addition, the class containing the test method has a TestClassAttribute attribute.

Both of these attributes are found in the:

Microsoft.VisualStudio.QualityTools.UnitTesting.Framework namespace.

Team Test uses reflection to search a test assembly and find all the TestClass decorated classes, and then find the corresponding TestMethodAttribute decorated methods to determine what to execute.

One other important criterion, validated by the execution engine but not the compiler, is that the test method signature be an instance method that takes no parameters.

The test method AddTest() instantiates the target SampleVB class before checking for assertion.

When the test is run, the Assert.Inconclusive() provides an indication that it is likely to be missing the correct implementation.



10. Providing input values to test method

Updated addTest() Implementation after editing to provide input values

 

Note that the checks are done using the Assert.AreEqual() method.

11. Running Tests:

To run all tests within the project simply requires running the test project. To enable this action, we need to:

Right-click on the VSTSVBDemo.Test project within the solution explorer and click Set as Startup Project.

Next, use the Debug->Start (F5) or Debug->Start Without Debugging (Ctrl+F5) menu items to begin running the tests.

 

To view additional details on the test, we can double click on it to open up the AddTest() Results:


Please note that the message in the assert statement does not appear for a "passing" test. It appears only when a test fails along with "Expected" and "Actual" values.

Lets assume that by mistake(even though its highly unlikely) we have put total=x*y instead of x+y in source code file. Let's try to run the same test and see the results:

 

Yes, as expected, test fails. Please read the results above for details.

12. Loading Test data from Database:

We are loading test data from SQL server database as below:

In Test View, right Click on AddTest()-->Properties-->Chose Data Connection String, Data Table Name and Data Access method as sequential or random.

 

This adds a line before test method as below:

<DataSource("System.Data.SqlClient", "Data Source=SUPRABHAT;Initial Catalog=I3LEMPLOYEES;User ID=userid;Password=" ", "TestTable1", DataAccessMethod.Sequential)> <testMethod> Public sub Addtest()

The Test Data is loaded from a Data table called: "TestTable1"

Here is the sample data in TestTable1:

Value1 Value2
1 10
22 25
589 236
56 202
45 56
879 563

13. Associating data with AddTest()

Within test method, change x and y as below:

Dim x As Integer = convert.ToInt32(testContextInstance.DataRow("Value1")
Dim y As Integer = convert.ToInt32(testContextInstance.DataRow("Value2")

The important characteristic here is the TestContext.DataRow calls. TestContext is a property that the generator provided when we Created Tests.

The test execution engine at runtime automatically assigns the property. so that within a test we can access data associated with the test context.

Now Run the testmethod. Please note results are available for each data row as below:

 

14. Code Coverage

  • On the Test menu, point to select Active Test Run Configuration. A submenu displays the entire test run configurations in the solution.
  • Click Code Coverage.
  • Under Select artifacts to instrument, check the box next to the solution.dll whose path is indicated as <Solution Directory>\ solutionname\bin\Debug.
  • Click Apply and click Close.
  • In Test Manager, check the boxes beside Testmethod/s, and click the Run Tests button or chose Run tests without debugging from Debug Menu.
  • On the Test Results toolbar, Right Click on Addtest() --> Code Coverage Results. The Code Coverage Results window opens.
  • In the Code Coverage Results window, the Hierarchy column displays one node that contains data for all the code coverage achieved in the latest test run. The test run node is named using the format <user name>@<computer name> <date> <time>. Expand this node.
  • Expand the node for the assembly, solution.dll.
  • The rows within the namespace class represent its methods. The columns in this table display coverage statistics for individual methods, for classes, and for the entire namespace.
  • Double-click the row for the Add(). The source-code file opens to the Add(). In this file you can see code highlighting. Lines highlighted green were exercised in the test run, and lines highlighted red were not. By scrolling, you can see the coverage for the other methods in this file.

9. Testing Private Methods

To generate a unit test for a private method

  1. Open a source code file that contains a private method.
  2. Right-click the private method and select Create Unit Tests.
  3. This displays the Create Unit Tests dialog box. In the visible tree structure, only check box for the private method is selected.
  4. (Optional) In the Create Unit Tests dialog box, you can change the Output project. You can also click Settings to reconfigure the way unit tests are generated.
  5. Click OK.
  6. This creates a new file named VSCodeGenAccessors, which contains special accessor methods that retrieve values of private entities in the class being tested. You can see the new file displayed in Solution Explorer in the test project folder.
  7. If your test project had no unit tests before this point, a source code file to house unit tests is also created. As with the file that contains private accessors, the file that contains unit tests is also visible in your test project in Solution Explorer.

  8. Open the file that contains your unit tests and scroll to the test for the private method. Find the statements that are marked with // TODO: comments and complete them by following the directions in the comments. This helps the test produce more accurate results.

  9. The unit test for the private method is now ready to run.

If the signature for a private method changes, you must update the unit test that exercises that private method.

Regenerate Private Accessors

  1. Open the source-code file that contains the private method that has changed.
  2. Right-click in this private method, point to Create Private Accessor, and select the test project into which to place the updated private accessors file.
  3. To the VSCodeGenAccessors file, this adds a new accessor class that contains methods for retrieving values of the entities in the private class being tested.
    Note: Do not edit the VSCodeGenAccessors file by hand.
  4. This creates up-to-date private accessors for all the private methods in your code-under-test file, whether private accessors for them existed previously.

10. Manual Testing

A manual test is a description of test steps that a tester performs. You use manual tests in situations where other test types, such as unit tests or Web tests, would be too difficult or too time consuming to create and run. You would also use a manual test when the steps cannot be automated, for example to determine a component's behavior when network connectivity is lost; this test could be performed by manually unplugging the network cable.

10.1. Creating Manual Tests and mapping them to MSVSTS

  • Right Click TestProject in Solution Explorer and then click New Test.
    The Add New Test dialog box appears. Under Templates is an icon for Manual Test (text format). If you have Microsoft Office 2003 installed, there is also an icon for Manual Test (Word format).
  • Click Manual Test (Word format).
  • For Test Name, change the name of the test to MyManualTest. Do not change the extension, .mht.
  • A new manual test with the name MyManualTest is added to the test project. The file MyManualTest is visible in Solution Explorer.
  • Click Test, point to Windows, and then click Test View, to display the Test View window. The test MyManualTest is visible in the Test View window.

10.2. To author a manual test

  • Follow the instructions in the test template. This means typing information about the test, including a description of the test, identification of the test target (the functionality you want tested), and the steps to be performed.
  • Save the manual test file.
  • The steps of your manual test are now ready to be run by a tester.

10.3. To execute a manual test

  • Click MyManualTest in the Test View window and then click Run Selection.
  • A dialog box appears. It explains that the test run will not complete until you have completed all the manual tests in the current test run.
  • Click OK.
  • The Test Results window shows a row for the test in which its result is displayed as Pending.
  • A dialog box appears. It alerts you that the manual test is ready to run.
  • Click OK.
  • The test itself is displayed in the main editing pane of the Visual Studio IDE, in a page whose tab is entitled MyManualTest [Running]. The lower section of the test page displays the steps of the test, while the upper section displays an area for the tester to input results. The results area consists of a Comments field and a pair of option buttons Pass and Fail.
  • Follow the steps of the test.
  • (Optional) While following the steps, type comments in the Comments field.
  • When you are finished, click either Pass or Fail to indicate the overall result of the test, and then click Apply.
  • The Test Results window displays the result that you chose.

11. Limitations of unit testing with MSVSTS 2005

  • Database operations testing: database testing is possible with Unit Testing approach but has certain disadvantages as given below.
  • Infinite looping

11.1. Database operations testing: two approaches

The first is to replace the database API that your DAL is talking to with an object of your own creation that mimics the database's interface, but does not actually perform any tasks. This method is often referred to as "mocking" or "stubbing.

The second testing method involves your DAL calling the real database behind the scenes. This usually means that you are performing state-based testing.

11.2. Using mock objects

  • No built in framework in MSVSTS: need to install and learn to use NMock or DBMock frameworks.
  • Does not test the database for successful operations.
  • Testing against mocks tends to be time consuming and counter-productive.
  • The mock that to be created tends be so complicated to mimic the database that the maintenance overhead will be too high.

11.3. Using state based testing approach

  • No standard frameworks for testing database after performing create, delete, update, and validate operations.
  • Need to write code in a TestMethod to check if correct operation was performed.
  • Test code tends to become larger than production code.

12. Best Practices

  • Avoid creating dependencies between tests such that tests need to run in a particular order. Each test should be autonomous. 
  • Use test initialization code to verify that test cleanup executed successfully and re-run the cleanup before executing a test if it did not run. 
  • Also Build Solution if any changes in Test code or source code to ensure accurate results every time.
  • Create one test class corresponding to each class within the production code. This simplifies the test organization and makes it easy to choose where to places each test. 
  • Use Visual Studio to generate the initial test project. This will significantly reduce the number of steps needed when manually setting up a test project and associating it to the production project. 
  • Verify that all tests run successfully before moving on to creating a new test. That way you ensure that you fix code immediately upon breaking it. 
  • Maximize the number of tests that can be run unattended. Make absolutely certain that there is no reasonable unattended testing solution before relying solely on manual testing.

13. Conclusion

Overall, the VSTS unit testing functionality is comprehensive on its own. Furthermore, the inclusion of code coverage analysis is invaluable to evaluating how comprehensive the tests are. By using VSTS, you can correlate the number of tests compared to the number of bugs or the amount of code written. This provides an excellent indicator into the health of a project.

This paper provides not only an introduction to the basic unit testing functionality in the Team Test Suite, but also delves into some of the more advanced functionality relating to data driven testing. By beginning the practice of unit testing your code, you will establish a suite of tests that will prove invaluable throughout the life of a product. Team Test makes this easy with its strong integration into Visual Studio and the rest of the VSTS product line.

원본 : http://www.c-sharpcorner.com/UploadFile/kgjawahar/DOTNETTESTING03172006002930AM/DOTNETTESTING.aspx?ArticleID=7dd17650-2884-448b-867c-56baa65e9c32


WRITTEN BY
hopangbear

트랙백  0 , 댓글  0개가 달렸습니다.
secret