Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It's not wrong to wrap up common code within your test classes, but I would avoid potentially sharing state between your tests.</p> <p>There are two approaches you can use here.</p> <h2>Class/Test Initialization</h2> <p>As <a href="https://stackoverflow.com/users/5620/peter-ritchie">Peter</a> mentions in his comments, it's easy enough to include initialization methods to do this sort of stuff for you.</p> <pre><code>//Only runs once per test run [ClassInitialize] public void InitClass(){ //Ideally this should be reserved for expensive operations // or for setting properties that are static throughout // the lifetime of your test. } //Runs for every test [TestInitialize] public void TestInit(){ //Here you can setup common stub/mock behavior // that will be common for every test, but ensure // it is clean for each test run } </code></pre> <h2>Setup/Factory Methods</h2> <p>Another option is to create specialized setup or factory methods that can be used to reduce repeated test code and make the intent of your test clearer.</p> <pre><code>[TestMethod] public void ShouldFailIfUserNameIsTed(){ var user = SetupUserScenario("Ted"); var result = _myUserService.Validate(user); Assert.IsFalse(result); } private User SetupUserScenario(String username){ var user = new User(); user.Name = username; //Do a bunch of other necessary setup return user; } </code></pre> <p>Hopefully this all makes sense, but I would also caution you not to go too crazy with this. If you put too much stuff into setup methods, then your tests will be less clear. You should be able to read the test and figure out what is going on without having to inspect a bunch of other places in the code.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload