Question

I am using NSubstitute for my Unit tests. I need to check that a object is send to a void method inside the method I am testing. I only need to check that the object is sent with one of the properties being a certain value.

eg.

///The object in question
public class Person
{
   public string Name { get; set; }
   public string Surname{get;set;}
}

Two simple methods

public void NameStartsWithA(Person person)
{
  //do something to person when name starts with A
}

public void NameStartsWithB(Person person)
{
  //do something to person when name starts with B
}

The method i am writing the test for.

public void MethodBeingTested()
{
  var person = new Person() {Name = "Adrian",Surname="SomeSurname"};

  if(person.Name.StartsWith("A"))
    NameStartsWithA(person);
  else
    NameStartsWithB(person);
}

If the person name starts with an A, I need to check, using NSubstitute that the "NameStartsWithA" was called with a name that starts with an A.

My Unit Test so far looks something like this

_someService.Received().NameStartsWithA(new Person(){Name="Adrian",Surname=Arg.Any<string>()});

But Nsubstitute says the function was never called, but when I do the same test with "RecievedArgumentsAny()" then it passes.

Hope this example helps you in understanding what I am trying to accomplish.

Was it helpful?

Solution

got this to work. Posting the code.

_someService.Received().NameStartsWith(Arg.Is<Person>(p => p.Name.Startswith== "A"));

hopes this will help someone in the future.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top