24.10.2012, 00:30. Показов 1715. Ответов 2
Что нужно добавить вручную в тест LoadFromFile, чтобы тест работал правильно. Принцип теста должен быть таким: (
тест который проверяет что, при вызове команды LoadFromFile класса MainViewModel запрашивает диалог открытия файла с расширением .txt)
Вот код Класса MainViewModel(здесь присутствует команда LoadFromFile) :
| C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using classLogically;
using WpfApplication.Misc;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using WpfApplicationIdialog;
using System.Collections.ObjectModel;
namespace WpfApplication.ViewMOdel
{
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
GridPeop = new ObservableCollection<Tarifs>();
GetTemplate = new RelayCommand(GetNewTamplate);
LoadFromFile = new RelayCommand(LoadFromFileExecute);
FindByNumber = new RelayCommand(FindByNumberExecute);
DelObj = new RelayCommand(DelMyObj);
AddToFile = new RelayCommand(AddTF);
}
#region Свойства
#region tarifs
public const string TarifsPropertyName = "tarifs";
private Tarifs _tarifs;
/// <summary>
/// Tarifs
/// </summary>
public Tarifs tarifs
{
get { return _tarifs; }
set
{
if (_tarifs == value)
return;
_tarifs = value;
RaisePropertyChanged(TarifsPropertyName);
}
}
#endregion
public ObservableCollection<Tarifs> GridPeop { get; private set; }
#region FileName
public const string FileNamePropertyName = "FileName";
private string _fileName;
/// <summary>
/// FileName
/// </summary>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName == value)
return;
_fileName = value;
RaisePropertyChanged(FileNamePropertyName);
}
}
#endregion
#region NumberToFind
public const string NumberToFindPropertyName = "NumberToFind";
private int _numberToFind;
/// <summary>
/// NumberToFind
/// </summary>
public int NumberToFind
{
get { return _numberToFind; }
set
{
if (_numberToFind == value)
return;
_numberToFind = value;
RaisePropertyChanged(NumberToFindPropertyName);
}
}
#endregion
#region LoadFromFile command
public RelayCommand LoadFromFile { get; private set; }
private void LoadFromFileExecute(object obj)
{
if (DialogService == null)
return;
var filename = DialogService.OpenFileDialog(_prevSelectedFilename, ".txt", "Текстовые файлы (.txt)|*.txt");
if (string.IsNullOrEmpty(filename))
return;
_prevSelectedFilename = filename;
var dataContext = new TarifsOpenFileText();
dataContext.FileName = filename;
try
{
_tarifssCollection.LoadTarifs(dataContext);
//GridPeop = null;
GridPeop.Clear();
foreach (var emp in _tarifssCollection.Tarifss)
{
GridPeop.Add(emp);
}
//ShowMessage(String.Format("Загружено {0} объектов", _employeeCollection.Count));
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
}
#endregion
#region NumberToDelete
public const string NumberToDeletePropertyName = "NumberToDelete";
private int _numberToDelete;
/// <summary>
/// NumberToFind
/// </summary>
public int NumberToDelete
{
get { return _numberToDelete; }
set
{
if (_numberToDelete == value)
return;
_numberToDelete = value;
RaisePropertyChanged(NumberToDeletePropertyName);
}
}
#endregion
#endregion
#region Команды
private string _prevSelectedFilename;
#region FindByNumber command
public RelayCommand FindByNumber { get; private set; }
private void FindByNumberExecute(object obj)
{
try
{
tarifs = _tarifssCollection.GetTarifs(NumberToFind);
if (tarifs == null)
ShowMessage(String.Format("Сотрудник с номером {0} не найден", NumberToFind));
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
}
#endregion
#region DelMyObj command
public RelayCommand DelObj { get; private set; }
private void DelMyObj(object obj)
{
try
{
Tarifs p = _tarifssCollection.search(NumberToFind);
_tarifssCollection.Remove(NumberToFind);
GridPeop.Remove(p);
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
}
#endregion
#region AddToFile command
public RelayCommand AddToFile { get; private set; }
private void AddTF(object obj)
{
if (DialogService == null)
return;
var filename = DialogService.SaveFileDialog(_prevSelectedFilename, ".txt", "Текстовые файлы (.txt)|*.txt");
if (string.IsNullOrEmpty(filename))
return;
_prevSelectedFilename = filename;
try
{
var dataContext = new TarifsOpenFileText();
dataContext.FileName = _prevSelectedFilename;
dataContext.AddToFileTarifi(_tarifs);
// MessageBox.Show("Содержимое записано в файл");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
#region Создание нового объекта
public RelayCommand GetTemplate { get; private set; }
private void GetNewTamplate(object obj)
{
try
{
int max = 1;
double max1 = 2;
double max2 = 3;
foreach (Tarifs tarifss in _tarifssCollection.Tarifss)
{
if (tarifss.Id > max)
{
max = tarifss.Id;
}
if (tarifss.PricePerMinute > max1)
{
max1 = tarifss.PricePerMinute;
}
if (tarifss.SetUpFee > max2)
{
max2 = tarifss.SetUpFee;
}
}
tarifs = null;
tarifs = new Tarifs();
tarifs.Id = max + 1;
tarifs.NameTarif = "TarifTest";
tarifs.TypeOfTariffication = "tes";
tarifs.PricePerMinute = max1 + 11;
tarifs.SetUpFee = max2 + 11;
_tarifssCollection.Add(tarifs);
GridPeop.Add(tarifs);
// ShowMessage(String.Format("Шаблон {0} получен", tarifs.Id));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
#endregion
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private TarifsCollection _tarifssCollection = new TarifsCollection();
public IDialogService DialogService { get; set; }
private void ShowMessage(string message)
{
//ShowMessage(message);
// Страшное нарушение шаблона MVVM!!! Хорошо, что этого не видела MVVM-полиция!
// Что, если мы захотим протестировать наш MainViewModel автоматическими юнит-тестами?
// MainViewModel начнёт выводить окошки сообщений в тестовой среде на нашем тест-сервере!
// Такое поведение практически исключает возможность написания модульных тестов
// для MainViewModel :-(
// Так было раньше.
// Но теперь всё в порядке - теперь MainViewModel не зависит от класса MessageBox,
// Вместо него у нас интерфейс IDialogService, который может быть реализован любым классом:
// - в работающем приложении это будет тот же вывод через MessageBox;
// - в тестовой среде это будет класс-заглушка.
if (DialogService != null)
DialogService.ShowMessage(message);
}
}
} |
|
И вот сам класс-тест в котором должен реализовываться тест(тест присутствует, но нужно что-то добавить) :
| C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
| using System;
using System.Windows;
using classLogically;
using WpfApplication;
using WpfApplication.ViewMOdel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WpfApplication.Misc;
using WpfApplicationIdialog;
namespace UnitTestProject
{
/// <summary>
///This is a test class for MainViewModelTest and is intended
///to contain all MainViewModelTest Unit Tests
///</summary>
[TestClass()]
public class MainViewModelTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
/// <summary>
///A test for FindByNumber
///</summary>
[TestMethod()] // таким атрибутом обозначаются тестовые методы
[DeploymentItem("WpfApplication.exe")]
public void FindByNumberTest_Поиск_несуществующего_сотрудника_устанавливает_Employee_в_null()
{
var mainViewModel = new MainViewModel();
mainViewModel.tarifs = new Tarifs(); // создаём сотрудника, чтобы перед выполнением теста свойство было != null
mainViewModel.NumberToFind = 1; // Задаём номер для поиска
mainViewModel.FindByNumber.Execute(null);
Assert.IsNull(mainViewModel.tarifs);
}
[TestMethod()]
[DeploymentItem("WpfApplication.exe")]
public void FindByNumberTest_Поиск_несуществующего_сотрудника_выводит_сообщение()
{
var mainViewModel = new MainViewModel();
var dialogServiceMock = new DialogServiceMock();
mainViewModel.DialogService = dialogServiceMock;
mainViewModel.NumberToFind = 1;
mainViewModel.FindByNumber.Execute(null);
if (string.IsNullOrEmpty(dialogServiceMock.LastShowMessage))
Assert.Fail();
}
private class DialogServiceMock : IDialogService
{
public string LastShowMessage;
public void ShowMessage(string message, string title = null)
{
LastShowMessage = message;
}
public MessageBoxResult ShowYesNoDialog(string message, string title)
{
throw new NotImplementedException();
}
public string OpenFileDialog(string defaultFilename, string defaultExt, string filter)
{
throw new NotImplementedException();
}
public string SaveFileDialog(string defaultFilename, string defaultExt, string filter)
{
throw new NotImplementedException();
}
}
private class DialogWindowMock : IDialogView
{
public bool CloseWindowExecuted = false;
public void ShowWindow()
{
// throw new NotImplementedException();
}
public bool? ShowWindowModal()
{
return true;
}
public void Show()
{
throw new NotImplementedException();
}
public void HideWindow()
{
throw new NotImplementedException();
}
public void CloseWindow()
{
CloseWindowExecuted = true;
}
public bool Activate()
{
// throw new NotImplementedException();
return true;
}
public void BindToViewModel(object viewModel)
{
}
}
}
}
namespace TestProject1
{
/// <summary>
///Это класс теста для MainViewModelTest, в котором должны
///находиться все модульные тесты MainViewModelTest
///</summary>
[TestClass()]
public class MainViewModelTest
{
private TestContext testContextInstance;
/// <summary>
///Получает или устанавливает контекст теста, в котором предоставляются
///сведения о текущем тестовом запуске и обеспечивается его функциональность.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Дополнительные атрибуты теста
//
//При написании тестов можно использовать следующие дополнительные атрибуты:
//
//ClassInitialize используется для выполнения кода до запуска первого теста в классе
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//ClassCleanup используется для выполнения кода после завершения работы всех тестов в классе
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//TestInitialize используется для выполнения кода перед запуском каждого теста
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//TestCleanup используется для выполнения кода после завершения каждого теста
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
/// <summary>
///Тест для LoadFromFile
///</summary>
[TestMethod()]
[DeploymentItem("WpfApplication.exe")]
public void LoadFromFileTest()
{
// Сбой при создании частного метода доступа для "Microsoft.VisualStudio.TestTools.TypesAndSymbols.Assembly"
Assert.Inconclusive("Сбой при создании частного метода доступа для \"Microsoft.VisualStudio.TestTools.T" +
"ypesAndSymbols.Assembly\"");
}
}
} |
|
Помогите пожалуйста. Заранее спасибо.