Unit Test Private methods in WP7
I want to write unit tests for my private methods in WP7 app code. So I would like to know how to call private methods from Silverlight Unit Test code. Below is a code snippet for which I would like to write unit test.
private void Next_Click(object sender, EventArgs e)
{
nextBtn.IsEnabled = false;
checking = true;
App app = Application.Current as App;
//Microsoft.Phone.Controls.TiltEffect.SetIsTiltEnabled((App.Current as App).RootFrame, true);
if (String.IsNullOrEmpty(AppHelper.AuthenticationToken))
{
// Get Authentication Token
try
{
app.Flickr.AuthGetTokenAsync(frob, r =>
{
Dispatcher.BeginInvoke(() =>
{
if (r.HasError)
{
MessageBox.Show("Flickr error (" + r.ErrorMessage + ") - did you click Ok before setting flickr up in your browser?");
}
else
{
// Store the authentication token
AppSettings.AuthenticationToken = r.Result.Token;
if (AppSettings.IsLoginIconPressed == false)
{
NavigationService.Navigate(new Uri("/Upload.xaml", UriKind.Relative));
}
else
{
app.isNavigatedFromPage = true;
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
AppSettings.IsLoginIconPressed = false;
开发者_StackOverflow }
}
checking = false;
});
});
}
catch (Exception ex)
{
MessageBox.Show("Flickr error (" + ex.Message + ") - did you click Ok before setting flickr up in your browser?");
}
} // End of if
else
{
if (AppSettings.IsLoginIconPressed == false)
{
app.isNavigatedFromPage = true;
NavigationService.Navigate(new Uri("/Upload.xaml", UriKind.Relative));
}
else
{
app.isNavigatedFromPage = true;
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
AppSettings.IsLoginIconPressed = false;
}
} // End of else
}
Just as with other .Net code you can use the InternalsVisibleTo attribute.
There is a description of this as well as several other WP7 specific things here.
One comment, however, is that wanting to unit test private methods is often a code smell - well factored code usually has a public interface that allows thorough unittesting without needing to specifically test the private methods.
In addition to the general comment on unit testing and private methods, I'd strongly recommend you look at the MVVM design pattern. The main reason you find yourself wanting to test the private next_click method is that you have put a whole lot of business logic within your UI code. MVVM is a pattern which places this sort of logic into easily testable Model and ViewModel classes and Silverlight has several features that make the pattern particularly easy to use.
Private means you can only call it from within the current class, not from outside. Unit-test is outside.
Make it public if you really want to test it directly, or change its visibility using other ways.
精彩评论