我开始编写单元测试(MS测试,Resharper作为测试运行器).当我设置LogicalThreadContext(见下文)时,我的测试用例被"中止".谁知道为什么?这与单元测试在不同的线程上有关吗?我该如何解决这个问题?
[TestClass]
public class ContextInfoTest
{
private ILog _log;
[TestInitialize]
public void TestInitialize()
{
// logging configured in assembly.info
_log = LogManager.GetLogger(this.GetType());
}
[TestMethod]
public void FigureOutWhyAborting()
{
string input = "blah";
LogicalThreadContext.Properties["mypropertyname"] = input;
string output = LogicalThreadContext.Properties["mypropertyname"] as string;
Assert.AreEqual(input, output);
}
[TestMethod]
public void ThisWorks()
{
string input = "blah";
CallContext.LogicalSetData("mypropertyname", input);
string output = CallContext.LogicalGetData("mypropertyname") as string;
Assert.AreEqual(input, output);
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是,如果我要调试并逐步执行代码,Assert.AreEqual会被调用并传递,因此在该行代码之后发生了一些事情...这就是为什么我认为它可能与某些事情有关测试线程等
谢谢!
更新:所以我在MSTest中运行了这个测试并得到了这个例外(Resharper没有显示它)
单元测试适配器抛出异常:成员'log4net.Util.PropertiesDictionary,log4net,Version = 1.2.13.0,Culture = neutral,PublicKeyToken = 669e0ddf0bb1aa2a'的类型未解析..
我在VS2013,.Net 4.5上使用log4net v1.2.13.
这个链接似乎暗示它是一个引用的程序集问题,但没有解决方案.非常欢迎任何其他想法,GAC'log4net不是一个选项. https://issues.apache.org/jira/browse/LOG4NET-398
我有一个执行FTP操作的ac..Net控制台应用程序.目前,我在自定义配置部分中指定设置,例如
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ftpConfiguration" type="FileTransferHelper.FtpLibrary.FtpConfigurationSection, FileTransferHelper.FtpLibrary" />
</configSections>
<ftpConfiguration>
<Environment name="QA">
<sourceServer hostname="QA_hostname"
username="QA_username"
password="QA_password"
port="21"
remoteDirectory ="QA_remoteDirectory" />
<targetServer downloadDirectory ="QA_downloadDirectory" />
</Environment>
</ftpConfiguration>
</configuration>
Run Code Online (Sandbox Code Playgroud)
我想在命令行中指定一个外部配置文件.
然而!!!...
我刚刚意识到上面的"FtpConfiguration"部分并不真正属于应用程序的app.config.我的最终目标是,我将有许多执行我的控制台应用程序的计划任务,如下所示:
FileTransferHelper.exe -c FtpApplication1.config
FileTransferHelper.exe -c FtpApplication2.config
...
FileTransferHelper.exe -c FtpApplication99.config
Run Code Online (Sandbox Code Playgroud)
因此,我相信我走错了路,我真正想要的是在我的自定义xml文档中读取的内容,但继续使用System.Configuration获取值...而不是读取XmlDocument并将其序列化为获取节点/元素/属性.(虽然如果有人能给我看一些简单的代码,我不反对后者)
指针将不胜感激.谢谢.
更新:我接受的答案是另一个StackOverflow问题的链接,在这里用我的代码重复 - 下面正是我正在寻找的 - 使用OpenMappedExeConfiguration打开我的外部配置文件
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = @"D:\Development\FileTransferHelper\Configuration\SampleInterface.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
FtpConfigurationSection ftpConfig = (FtpConfigurationSection)config.GetSection("ftpConfiguration");
Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个公共类的接口,但实现类可以有不同的参数.
例如
public interface IViewModel
{
//...
void ResetReferences();
}
// and then, in my class implementations, something like this:
public class LocationViewModel : IViewModel
{
public void ResetReferences(List<StateProvinces> stateProvinces) //...
}
public class ProductViewModel : IViewModel
{
public void ResetReferences(List<Color> colors, List<Size> sizes) //...
}
Run Code Online (Sandbox Code Playgroud)
所以请注意我想要标准化"RestReferences"命名约定.我很确定我不能这样做,但是有没有可行的设计模式?例如在我的界面中,如下所示?
// variable parameters
void ResetReferences(params object[] list);
Run Code Online (Sandbox Code Playgroud)
但是,我如何让我进行类型检查或让它调用我想要的实际方法签名等?
也许界面是错误的使用?也许只是一个基类和一些编码约定?
谢谢,
我试图将两个列表/集合合并(联合或concat).这两个列表有一个共同的基类.我试过这个:
IQueryable<ContractItem> contractItems = myRepository.RetrieveContractItems();
IQueryable<ChangeOrderItem> changeOrderItems = myRepository.RetrieveChangeOrderItems();
IQueryable<ItemBase> folderItems = contractItems.Concat<ItemBase>(changeOrderItems);
Run Code Online (Sandbox Code Playgroud)
但是我得到LINQ错误DbUnionAllExpression需要带有兼容集合ResultTypes的参数.
有谁知道如何正确地做到这一点?我唯一可以google的是另一个StackOverflow问题: 具有相同基类的LINQ Union对象
谢谢.
我正在使用AutoMapper 3.2.1
我只是要求我的项目的消费者希望我做一些简单的转换 - 将所有字符串字段修剪为空格并将null转换为string.empty.
如何以高效的方式在AutoMapper中执行此操作?
例如
public class Person()
{
public string First {get; set;}
public string Middle {get; set; }
public string Last {get; set; }
public DateTime DateOfBirth {get; set; }
}
public class PersonDto()
{
public string First {get; set;}
public string Second {get; set; }
public string Last {get; set; }
public DateTime DateOfBirth {get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的地图示例:
Mapper.CreateMap<Person, PersonDto>().
.ForMember(dst => dst.Second, opt => opt.MapFrom(src => src.Middle));
Mapper.CreateMap<PersonDto, Person>().
.ForMember(dst => dst.Last, opt …Run Code Online (Sandbox Code Playgroud) 我正在创建一个以无限循环运行的消费者来读取队列中的消息.我正在寻找关于如何在我的无限循环中继续恢复abd的建议/示例代码,即使存在网络中断.消费者必须保持运行,因为它将作为WindowsService安装.
1)有人可以解释如何正确使用这些设置吗?他们之间有什么区别?
NetworkRecoveryInterval
AutomaticRecoveryEnabled
RequestedHeartbeat
Run Code Online (Sandbox Code Playgroud)
2)请查看我当前的消费者示例代码.我使用的是.Net RabbitMQ Client v3.5.6.
以上设置如何为我"恢复"?例如,consumer.Queue.Dequeue阻止,直到它被恢复?这似乎不对......
我是否需要手动编写代码?例如,consumer.Queue.Dequeue抛出一个异常,我必须检测并手动重新创建我的连接,通道和消费者?或者只是消费者,因为"AutomaticRecovery"会为我恢复频道?
这是否意味着我应该在while循环中移动消费者创造?那么频道创作呢?和连接创建?
3)假设我必须手动执行一些恢复代码,是否有事件回调(以及如何注册它们)告诉我有网络问题?
谢谢!
public void StartConsumer(string queue)
{
using (IModel channel = this.Connection.CreateModel())
{
var consumer = new QueueingBasicConsumer(channel);
const bool noAck = false;
channel.BasicConsume(queue, noAck, consumer);
// do I need these conditions? or should I just do while(true)???
while (channel.IsOpen &&
Connection.IsOpen &&
consumer.IsRunning)
{
try
{
BasicDeliverEventArgs item;
if (consumer.Queue.Dequeue(Timeout, out item))
{
string message = System.Text.Encoding.UTF8.GetString(item.Body);
DoSomethingMethod(message);
channel.BasicAck(item.DeliveryTag, false);
}
}
catch (EndOfStreamException ex)
{
// …Run Code Online (Sandbox Code Playgroud) 在常规.net中,如果我们有一个具有DateTimeKind.Unspecified的时间如果我们转换ToLocal - 它假定转换时输入日期是UTC.如果我们转换ToUniversal - 它假定转换时输入日期是本地的
但是,在JSON.Net中,如果我们在JSON.Net中的字符串日期未指定,它似乎没有这个逻辑?看看我下面的测试用例 - 我做错了吗?或者这是设计?或JSON.Net中的错误?谢谢!
// TODO: This Fails with output
// date string: "2014-06-02T21:00:00.0000000"
// date serialized: 2014-06-02T21:00:00.0000000Z
// Expected date and time to be <2014-06-03 04:00:00>, but found <2014-06-02 21:00:00>.
[TestMethod]
public void NEW_Should_deserialize_unspecified_datestring_to_utc_date()
{
string dateString = "\"2014-06-02T21:00:00.0000000\"";
DateTime dateRaw = new DateTime(2014, 6, 2, 21, 0, 0, 0, DateTimeKind.Unspecified);
DateTime dateRawAsUtc = new DateTime(2014, 6, 3, 4, 0, 0, 0, DateTimeKind.Utc);
dateRawAsUtc.Should().Be(dateRaw.ToUniversalTime());
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
settings.DateFormatHandling = DateFormatHandling.IsoDateFormat; …Run Code Online (Sandbox Code Playgroud) 我正在使用MVC3并在我的应用程序中有区域.一般来说,一切正常,我可以导航到我的区域(例如Admin = Area,Controller = Department),如下所示:
<%: Html.ActionLink("Departments", "DepartmentIndex", "Department", new { area = "Admin"}, null )%>
Run Code Online (Sandbox Code Playgroud)
但是,我注意到的是,如果我没有在ActionLink中指定区域,例如
<%: Html.ActionLink("Test", "Index", "Home")%>
Run Code Online (Sandbox Code Playgroud)
如果我已导航到"管理员"区域,这将停止工作.即我的网址现在是 http:// localhost/myproj/Admin/Home/Index 而不是 http:// localhost/myproj/Home/Index
关于这里发生了什么的任何想法?
创建MVC应用程序/区域时,我的路由是所有默认值.即
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "MyProj.Controllers" }
);
}
Run Code Online (Sandbox Code Playgroud)
我的区域注册
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id …Run Code Online (Sandbox Code Playgroud) 我在我的nUnit测试用例中使用Moq.
这是我的测试用例的样子:
IList<ChartFieldDepartment> coaDepartments = new List<ChartFieldDepartment>() {
new ChartFieldDepartment { ChartFieldKey="1000", Description="Corporate Allocation"},
new ChartFieldDepartment { ChartFieldKey="1010", Description="Contribution to Capital"}
};
Mock<IChartFieldRepository> mockChartFieldRepository = new Mock<IChartFieldRepository>();
mockChartFieldRepository.Setup(x => x.RetrieveChartFieldDepartments(It.IsAny<bool>())).Returns(coaDepartments.AsQueryable);
ChartFieldDomainService chartFieldDomainService = new ChartFieldDomainService(mockChartFieldRepository.Object);
// this line fails! I get System.Reflection.TargetParameterCountException : Parameter count mismatch
IQueryable<ChartFieldDepartment> departments = chartFieldDomainService.RetrieveChartFieldDepartments();
Run Code Online (Sandbox Code Playgroud)
这是我的ChartFieldDomainService:
public class ChartFieldDomainService : IChartFieldDomainService
{
private IChartFieldRepository _chartFieldRepository = null;
public ChartFieldDomainService(IChartFieldRepository repository)
{
_chartFieldRepository = repository;
}
public virtual IQueryable<ChartFieldDepartment> RetrieveChartFieldDepartments()
{
return _chartFieldRepository.RetrieveChartFieldDepartments(true); // …Run Code Online (Sandbox Code Playgroud) 对于我的log4net解决方案,我有一个使用CallerInfo属性的API包装器,例如
public void Write(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int lineNumber = 0)
Run Code Online (Sandbox Code Playgroud)
但是,我也使用Unity Interception,以便我可以执行前/后响应的跟踪日志记录,例如在Invoke方法中使用如下所示的ICallHandler.
public class TraceCallHandler : ICallHandler
{
...
public IMethodReturn Invoke(IMethodInvocation input,
GetNextHandlerDelegate getNext)
{
//---- Trace method inputs
this.LogInfoBeforeInvoke(input);
//---- invoking the target method
InvokeHandlerDelegate next = getNext();
IMethodReturn methodReturn = next(input, getNext);
//---- invoking the target method
this.LogInfoAfterInvoke(methodReturn.ReturnValue);
}
}
Run Code Online (Sandbox Code Playgroud)
注意:上面的代码绝不是完整/正确的...但只是想告诉你我为Unity Interception做了些什么.
我的问题/挑战是这样的:当我最终调用log.Write(...)时,我想要目标的调用者信息,而不是我的TraceCallHandler信息.
例如,对于方法名称,我可以这样做:
string methodName = input.MethodBase.Name;
Run Code Online (Sandbox Code Playgroud)
如何获取来电者的文件路径和来电者的线路号码?甚至可以通过反思来做吗?
谢谢!
c# ×5
.net ×2
log4net ×2
areas ×1
automapper ×1
covariance ×1
datetime ×1
formatter ×1
global ×1
interception ×1
interface ×1
json.net ×1
linq ×1
methods ×1
moq ×1
parameters ×1
rabbitmq ×1
reflection ×1
routes ×1
timezone ×1
union ×1
unit-testing ×1