Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8477287
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T18:25:22+00:00 2026-06-10T18:25:22+00:00

I have a test class with a couple tests that check to see if

  • 0

I have a test class with a couple tests that check to see if the entity IsValid. I moved to using IValidatableObject from having my own custom validation but I’m stuck with the correct validation technique.

This is my Test class:

[TestFixture]
public class StudentTests {
    private static Student GetContactWithContactInfo()
    {
        return new Student(new TestableContactRepository())
                            {
                                Phone = "7275551111"
                            };
    }

    private static Student GetContactWithoutContactInfo()
    {
        return new Student(new TestableContactRepository());
    }

    [Test]
    public void Student_Saving_StudentHasInfo_IsValid ()
    {
        // Arrange
        Student student = GetContactWithContactInfo();
        // Act
        student.Save();
        // Assert
        Assert.IsTrue(student.IsValid);
    }

    [Test]
    public void Student_Saving_StudentDoesNotHaveInfo_IsNotValid ()
    {
        // Arrange
        Student student = GetContactWithoutContactInfo();
        // Act
        student.Save();
        // Assert
        Assert.IsFalse(student.IsValid);
    }
}

This is my entity:

public class Student : IValidatableObject
{
    private readonly IContactRepository contactRepository;

    public Student(IContactRepository _contactRepository)
    {
        contactRepository = _contactRepository;
        Contacts = new List<Student>();
    }

    [Required]
    public int Id { get; private set; }

    [StringLength(10, MinimumLength = 10)]
    public string Phone { get; set; }


    public List<Student> Contacts { get; private set; }

    public bool IsValid { get; private set; }

    public void Save()
    {
        if (IsValidForPersistance())
        {
            IsValid = true;
            Id = contactRepository.Save();
        }
    }

    private bool IsValidForPersistance()
    {
        return Validator.TryValidateObject(this, new ValidationContext(this), null, true);
    }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (string.IsNullOrEmpty(Phone) && Contacts.All(c => string.IsNullOrEmpty(c.Phone)))
            yield return new ValidationResult("The student or at least one contact must have a phone number entered", new[] { "Phone Number" });
    }
}

As you can see the tests test for IsValid by calling the IsValidForPersistance. Validate will eventually have more validation .

The above tests all pass using this method but this test below also passes but should not.

[Test]
public void Student_Saving_HasContactInfoWithInvalidLength_IsNotValid()
{
    // Arrange
    Contact student = GetContactWithoutContactInfo();
    student.Phone = "string";

    // Act
    student.Save();

    // Assert
    Assert.IsFalse(student.IsValid);
}

Here I’m setting my own Phone value of an invalid length string. I expect validation to fail because of the StringLength annotation set at min and max 10 characters.

Why is this passing?

Update
There was a problem with the custom validation, updated the code with the change. Along with the suggestion from nemesv about not having a private modifier on the Phone property it now works. I’ve updated all the code to working.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T18:25:24+00:00Added an answer on June 10, 2026 at 6:25 pm

    Validator.TryValidateObject only checks the RequiredAttributes (and also other things like type level attributes and IValidatableObject implementation) by default.

    If you need to validate all the attributes like StringLength etc. you need to set the validateAllProperties parameter of the method to true

    private bool IsValidForPersistance() {
        return Validator.TryValidateObject(this, 
                                           new ValidationContext(this), 
                                           null,
                                           true /* validateAllProperties */);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Test Class, that test the access of all page with different
I have a trait that adds a couple of tests and before blocks. The
I have a couple Java classes which have blackbox test cases that just exercise
I have a number of JUnit tests in my project that test my DataStore
I have some test class TestKlass = (function() { function TestKlass(value) { this.value =
I have following test class @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {/services-test-config.xml}) public class MySericeTest { @Autowired
Lets say I have a test class called ServiceTest with three test methods test1,
If I have: class Test { private Vector2 v; public Vector2 Velocity { get
say I have: class Test { public static int Hello = 5; } This
I have a JUnit test class in which I have several static final int

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.