Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSubstitute with object as parameter in Received call

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.

like image 457
Captain0 Avatar asked Jan 29 '13 06:01

Captain0


1 Answers

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.

like image 175
Captain0 Avatar answered Sep 20 '22 01:09

Captain0