I have a web page that shows different messages according to different conditions. I want to unit test this so I configured my project to use MVVM and I'm testing my ViewModel.
My ViewModel now format different messages. How can I test this? I don't want to reproduce all strings, it seems dirty...
Now I'm doing this:
void test()
{
string message = _viewModel.DoWork();
Assert.AreEqual(message, Resource.MyResource开发者_开发百科Text);
}
But this is a simple case. Now I have dynamic strings containing system date and other variables.
How can I test this in an elegant way? Thanks!
If your concern is just reproducing strings in your test fixtures, put them all in an enum
or class
.
public static class StatusMessage
{
public static readonly string SavedSuccessfully
= "Item was successfully saved.";
public static readonly string DuplicateRecord
= "This record is a duplicate.";
public static readonly string SubscriptionExpired
= "Your subscription has expired; please renew now.");
}
Now your viewmodel can perform its logic and return one of the StatusMessages:
public class SomeViewModel
{
...
public string Status
{
get { return StatusMessage.SavedSuccessfully; }
}
...
}
In your test:
Assert.AreEqual(StatusMessage.SavedSuccessfully, viewmodel.Status);
I will go with what you are currently doing or may be what @Jay has suggested.
But, I really don't understand when you say,
Now I have dynamic strings containing system date and other variables.
The expected string always HAS to be hardcoded in order to unit test it. You should never ever use any calculation in unit test. You should set a scenario (date, any other vars) and then you know what your expected string will be. You will then hardcode it.
If you want to unit test the same method for different strings you can use TestCase
attribute in nunit or RowTest
attribute in MBUnit.
I resolved in this way:
class MyTestClass
{
void test()
{
string message = _viewModel.DoWork();
MyAssert.StringFormatConforms(message, Resource.MyResourceText);
}
}
class MyAssert
{
public static void StringFormatConforms(string stringToCheck, string format)
{
// replace {0}, {1} with .*
string regex = "^" + Regex.Replace(format, "{[0-9]+}", ".*") + "$";
bool conforms = Regex.IsMatch(stringToCheck, regex);
if (!conforms)
throw new AssertFailedException(String.Format("The string {0} does not conforms to format: {1}", stringToCheck, format));
}
}
In this way I can check that my message "hi ric" must conform to "hi {0}"
精彩评论